Reputation: 334
Hello I'm trying to send the ID in an dynamic way here is the code:
function formsub(val){
val2 = "form#" + val.toString() + " :input";
val3 = "form#formmain :input";
$(val3).each(function () {
var input = $(this);
alert($(this).val());
});
}
When someone click a submit button in the form this will call formsub
but the problem I get and error:
Uncaught exception: Syntax error , unrecognized expression ''
I try to use val3
and it's working fine but when I use val2
it give me the error but they are the same value.
<form id='formmain' method='post' onsubmit='formsub(this.id)'>
<label>Name</label>
<input type='textbox' required />
<span style='color:red;'>*</span>
<br/>
<label>Male</label>
<input type='radio' required />
<span style='color:red;'>*</span>
<br/>
<label>Female</label>
<input type='radio' required />
<span style='color:red;'>*</span>
<br/>
<input type='submit' />
<br/>
</form>
The code above is for the form.
Thanks in advance
Upvotes: 2
Views: 81
Reputation: 121998
Try
$("form#" + val.toString() + ":input").each(function(){
var input = $(this);
alert(input.val());
});
Upvotes: 1
Reputation: 73896
Replace this:
val2 = "form#" + val.toString() + ": input"; // form#formmain: input
with this:
val2 = "form#" + val.toString() + " :input"; // form#formmain :input
Also a suggestion, since ID are supposed to be unique, you can just use the ID instead of form#ID
, like:
val2 = "#" + val.toString() + " :input"; // #formmain :input
Also, you can modify the js like:
function formsub(val) {
val2 = "#" + val.toString() + " :input";
val3 = "#formmain :input";
$(val2).each(function () {
alert(this.value);
});
}
Upvotes: 2
Reputation: 816262
As already mentioned by others and by me, the position of the colon is different in both strings and that's why you get the error in one case.
However, you can avoid the whole string concatenation if you work directly with the DOM element.
HTML:
<form id='formmain' method='post' onsubmit='formsub(this)'>
JS:
function formsub(ele){
$(ele).find(':input').each(function () {
// ...
});
}
Even better if use jQuery to bind the event handler, e.g.:
$('form').on('submit', formsub);
// or $('#formmain').on('submit', formsub);
Inside the event handler, this
will refer to the form element then. Learn more about event handling: http://learn.jquery.com/events/.
Upvotes: 3
Reputation: 388316
No space between :
and input
it should be :input
function formsub(val){
val2="form#" + val.toString() + ":input"; // no space between : and input
val3="form#formmain :input";
$(val3).each(function(){
var input = $(this);alert($(this).val());
});
}
Upvotes: 2
Reputation: 15603
As I have analysis the code, I see that there is minor difference between val2 and val3:
Replace your val2 with this:
val2="form#"+val.toString()+" :input";
As you have forgot the space.
Upvotes: 2
Reputation: 1260
Try to use
val2="form#"+val+" :input";
Let me know is this helpfull?
Upvotes: 2