Testing .attr and .val
This fiddle allows one to experiment with jquery .val() and .attr('value',...) on text input fields.
by jasonnet
HTML
<form>
<table border=1>
<tr>
<th>value= in static html element</th>
<td>no</td>
<td>yes</td>
</tr>
<tr>
<th>input/visual:</th>
<td>
<input type=text id=tnameid class=in1 name=tname>
</td>
<td>
<input type=text id=tnameid class=in2 name=tname value='initial value'>
</td>
</tr>
<tr>
<th>attr('value') returns:</th>
<td><span id=tvalue_in1></span></td>
<td><span id=tvalue_in2></span></td>
</tr>
<tr>
<th>val() returns</th>
<td><span id=tval_in1></span></td>
<td><span id=tval_in2></span></td>
</tr>
</table>
</form>
<h3>Buttons</h3>
<button type="button" id=button3>set via .val(...)</button>
<br/>
<button type="button" id=button4>set via .attr('value',...)</button>
<br/>
<br/>
<br/>count: <span id=tcount></span>
<hr/>
<h3>
Help:
</h3>
<p>
You may use the buttons to call the setter methods just mentioned. You may also type directly in to the text entry fields to understand the impact of user input.
</p>
<p>
There are two text entry fields above. First is uninitialized by the original static html. The second is initialized by a value= attribute in the original html. Experimenting with both of these fields can help you understand how static value= initialization
impacts the behavior of the page.
</p>
<p>Good luck.</p>
Jason.
CSS
th {
text-align: right;
background-color: #ddd
}
table {
padding: 2px;
background-color: #eeeeee;
}
JavaScript
var count = 0;
function set_via_val() {
$('form input[name="tname"]').val('set via val() at ' + count);
}
function set_via_attr() {
$('form input[name="tname"]').attr('value', 'set via attr() at ' + count);
}
$('#button3').click(set_via_val);
$('#button4').click(set_via_attr);
function update() {
$('#tvalue_in1').text(' ' + $('input.in1').attr('value'));
$('#tval_in1').text(' ' + $('input.in1').val());
$('#tvalue_in2').text(' ' + $('input.in2').attr('value'));
$('#tval_in2').text(' ' + $('input.in2').val());
$('#tcount').text(count++);
}
setInterval(update, 1000);
update();