JQuery dynamically adding a hidden field

$().ready(function() { $("#add").click(function() { var vals = $("#txtaddfeature").val(); if(vals !='') $('#FeatureLists').prepend('<option value="' + vals + '" selected="selected">' + vals + '</option>'); $('#txtaddfeature').val(''); }); }); 

After adding the value to the selection list as above

 $('#FeatureLists').prepend('<option value="' + vals + '" selected="selected">' + vals + '</option>'); 

I want to create a dynamic hidden field with the above id = vals and set its value to the value entered in the text field. How can i do this

+6
jquery
source share
3 answers

I could not say exactly what you wanted. It looks like you want the ID and value new hidden input be the vals value. Is it correct?

 var $hiddenInput = $('<input/>',{type:'hidden',id:vals,value:vals}); 

Then you add it wherever you want.

 $hiddenInput.appendTo(selector); 

EDIT:

For clarification, selector is a reference to the element into which you want to add a new entry.

If you want to add it to the body tag, follow these steps:

 $hiddenInput.appendTo('body'); 

If you want to add it to an element with someClass class, do:

 $hiddenInput.appendTo('.someClass'); 
+20
source share

I would set to see if it was on the first page and then add.

 function SetHiddenInput(val) { var $txtaddfeaturehidden == $("#txtaddfeaturehidden"); if ($txtaddfeaturehidden.length == 0) { $("input").attr({ id : "txtaddfeaturehidden", type : "hidden", value : $('#txtaddfeature').val() }).after('#txtaddfeature'); } else $txtaddfeaturehidden.val(val); } 
+2
source share

You can do this:

 $("input").attr("type", 'hidden').val($('#txtaddfeature').val()).appendTo('selector_here'); 
+1
source share

All Articles