Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and remove an HTML hidden field using jQuery?

First of all here is my code so that you can test it to see what's wrong: JSFiddle

I want to create a new hidden field every time the user selects from the left <select> element and remove / destroy the hidden field when the user clicks the right <select> element.

I used the jQuery command $("<input type='hidden' value=selectedAddFootballPlayerId>"); but when I checked of Firebug I can't see any hidden field being created. For removal of the hidden field I really don't know.

like image 935
NinjaBoy Avatar asked Nov 30 '22 07:11

NinjaBoy


2 Answers

For this you can use .append().

$("body").append("<input type='hidden' value=selectedAddFootballPlayerId>");

For removal, use .remove().

$("input[type='hidden']").remove();

Be careful when using my example, as it'll remove all form elements that are hidden. If you want more prescision, you can assign an id value to the hidden input and then call that as your selector in the second example.

like image 57
esqew Avatar answered Dec 04 '22 09:12

esqew


To create -

var $ip = $('<input>').attr({
    type: 'hidden',
    id: 'yourid',
    name: 'yourname',
    value: 'yourvalue' 
})
$(ip).appendTo('body');

Then to remove -

$ip.remove();
like image 32
ipr101 Avatar answered Dec 04 '22 11:12

ipr101