jQuery

jQuery Replace Textbox With Another Element Examples

When working with different form elements, there might have been a time when you needed to replace a certain element in the form with another. In this article, I am going to share with you an easy way to replace a form element with another & specifically, use jQuery to replace textbox with another element. Examples follow.

How to use jQuery to Replace Textbox With Another Element

Let’s consider that we have a textbox with ID “states’. We would like to replace this textbox with a textarea with ID “message”. Let’s see how this textbox replacement can be done using jQuery.

Example 1: Replace Textbox with Textarea using jQuery

<form name="form1" id="form1" method="post" action="#">

<div id="states_container">
<label for="states">States</label>

<input type="text" name="states" id="states">
</div>

<br>

<input type="submit" name="sbt_replace_textbox_with_textarea" id="sbt_replace_textbox_with_textarea" value="Replace Textbox With Textarea" />

<input type="button" name="sbt_reset" class="reset" value="Reset">

</form>

<script type="text/javascript" language="javascript" >
// <![CDATA[	
$(document).ready(function(){

$('#sbt_replace_textbox_with_textarea').click(function(e) {

	$('#states').replaceWith( $('<textarea id="message">') );

	e.preventDefault();

});

});	
// ]]>			
</script>

When you run the above code & hit the Replace Textbox With Textarea button, you will see that the textbox will be instantly replaced with the textarea. Simply click on “Reset” button to reset the form to it’s original state.

Example 2: Replace Textbox with Select Dropdown using jQuery

<form name="form1" id="form1" method="post" action="#">

<div id="states_container">
<label for="states">States</label>

<input type="text" name="states" id="states">
</div>

<input type="submit" name="sbt_replace_textbox_with_select" id="sbt_replace_textbox_with_select" value="Replace Textbox With Select" />

<input type="button" name="sbt_reset" class="reset" value="Reset">

</form>

<script type="text/javascript" language="javascript" >
// <![CDATA[	
$(document).ready(function(){

$('#sbt_replace_textbox_with_select').click(function(e) {

	$('#states').replaceWith( $('<select id="cities"><option value="TX">TX</option></select>') );

	e.preventDefault();

});

$('.reset').click(function(e) {

	location.reload();

});

});	
// ]]>			
</script>

When you run the above code & hit the Replace Textbox With Select button, you will see that the textbox will be instantly replaced with the Select Dropdown. Simply click on “Reset” button to reset the form to it’s original state.

That’s it!

Do you know of any other ways to use jQuery to replace Textbox? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*