JQuery Mobile: .val() not working
Greetings,
I have the following jQuery Mobile code:
<div data-role="content">
A confirmation code has been sent to your mobile phone via SMS
<br><br>
To proceed, please enter the 3-digit c开发者_C百科onfirmation code below:
<br>
<input id="verifySMS_code" type="text" /><br>
<a id="verifySMS_submit" href="#" data-role="button">Submit</a>
</div>
Here is my javascript:
$(document).ready(function(){
$("#verifySMS_submit").live("click",function() {
alert('hi');
var code=$('input#verifySMS_code').val();
alert(code);
});
});
'hi' appears in the first alert box, however '' appears in the second alert box - i.e. totally blank!!!
I've tried document.getElementById('verifySMS_code') too to no avail.
I've even tried jquery mobile 1.0a3pre
This is a really serious problem for me and I've no idea how to fix it.
I hope someone can help.
Many thanks in advance,
Install firebug
Test it with
<input id="verifySMS_code" type="text" value="someoldvalue" />
and
$(document).ready(function(){
$("#verifySMS_submit").bind("submit",function() {
console.log($('#verifySMS_code'));
var code=$('#verifySMS_code').val();
console.log(code);
});
});
This is why:
- the
value=
in the input will show if it's a problem with getting the value or with putting what you enter into the input element (jquery mobile builds something on the input) - you will not generate new submit buttons matching "#verifySMS_submit"
so you don't need
live()
there - try it with click and with submit. I suppose jquery mobile is putting
text from the input control to the
input itself at some certain moments
like
blur
event on the input, so it happens when you click something else, not before that console.log($('input#verifySMS_code'));
will pop up your element in console. if empty array pops up - there was no such element and it's a selector problem.
Test for inputs with duplicated IDs.
This shows all ids: $('input').each(function(){console.log($(this).attr('id'));});
Run it in firebug and it will also point to DOM so you can click and find them in HTML tab.
I had the same problem. Somehow, it looks like JQuery Mobile doesn't handle well the syntax ("#someId")
Instead, doing ("input[id=verifySMS_code]").val()
should help
If You have get duplicate id's (after page loading or using changePage()
etc.) then try accessing the children of the active page object ...
Ex.
var myval = $('form#src #search').val(); // returns incorrect (:first) value of the element
replace with
var myval = $.mobile.activePage.find('form#src #search').val();
Anyway, worked form me:)
I had the same problem on a particular page. Then I realized I had some code that was calling a changePage()
to the same page, thereby duplicating the dom element and its id.
精彩评论