Reputation: 544
I need a function to add new input element dynamically using jQuery.
It is something like this
function addInput(inputName) {
$('<input>', {
type: "hidden",
name: "inputName"
}).appendTo('#foo');
}
addInput('test');
and it works, It adds a new <input type="hidden" name="test">
to #foo
Problem appears when I want to make this function add input only if input with specified name does not exists in DOM
.
Here is my updated function
function addInput(inputName) {
if (! $(input).attr('name','inputName') {
$('<input>', {
type: "hidden",
name: "inputName"
}).appendTo('#foo')
}
}
addInput('test');
But insteed checking for input
elements with the name test
it sets name of all input
elements to test
.
Is there any method to only test input name?
Upvotes: 2
Views: 14775
Reputation: 40639
Check length
with equal-selector like,
function addInput(inputName) {
if (! $('input[name="'+inputName+'"]').length) {
$('<input>', {
type: "hidden",
name: inputName
}).appendTo('#foo')
}
}
Upvotes: 9
Reputation: 11
if you work with jQuery just use .is()
function:
if(input.is('[name="your_name"]')){
//do some things!
}
Upvotes: 1
Reputation: 9947
function addInput(inputName) {
if ($('input[name="'+inputName+'"]').length > 0)
{
alert("Exists");
}
}
Upvotes: 2