Reputation: 12138
I have a text input field called locEmailMsg:
<input type="text"
class="phColor"
data-placeholder="Your email address"
maxlength="50"
style="font-size: 14px; width: 232px;"
id="locEmailMsg">
In my $(document).ready()
function, I need to do a few things: set the value of the input, set the data-placeholder attribute, and remove the phColor class.
$('#locEmailMsg').val(localStorage.email);
$('#locEmailMsg').attr('data-placeholder', localStorage.email);
$('#locEmailMsg').removeClass('phColor');
The data-placeholder attribute is being set correctly (watching in Firebug), but the value isn't being set, nor is the class being removed. Why would one part work, but the other parts not work?
This is part of a very large system, but I've stepped through all of the scripts as the page loads, and there's nothing happening after this call that's reversing the value set/class removal.
Upvotes: 3
Views: 10444
Reputation: 79830
Your code looks fine and It should work fine.. If it doesn't work then there must be some other issue that might be bugging that line..
I would try following to check where it is failing,
console.log
or alert
the value of localStorage.email
to see if the value is proper.document.getElementById('locEmailMsg').value = localStorage.email;
to make sure it is not jQuery issue.Upvotes: 2
Reputation: 22054
It works here with your code as you have it.
However, if an item with the same id occurs again, only the first will be affected. See here:
It doesn't matter if it's an input or not. IDs must be unique.
I put it in a timeout, so you can see the change
window.setTimeout(function() {
var localStorage = { email: '[email protected]' };
$('#locEmailMsg')
.val(localStorage.email)
.attr('data-placeholder', localStorage.email)
.removeClass('phColor');
}, 500);
And here is the failing html (only affects first item)
<input type="text"
class="phColor"
data-placeholder="Your email address"
maxlength="50"
style="font-size: 14px; width: 232px;"
id="locEmailMsg"
value="novalue" />
<div id="locEmailMsg">dupid</div>
<input type="text"
class="phColor"
data-placeholder="Your email address"
maxlength="50"
style="font-size: 14px; width: 232px;"
id="locEmailMsg"
value="novalue" />
This is the only way I can see your code not working.
EDIT
Run this on your page to make sure you don't have duplicate ids
$('[id]').each(function(){
var ids = $('[id="'+this.id+'"]');
if(ids.length>1 && ids[0]==this)
alert('Multiple IDs #'+this.id);
});
Upvotes: 4