-1

I don't understand the difference beetwen Jquery .attr() and .prop(). In my website i need to open a popup and inside that I have a form. Now i wonder to know how can I change the state.

If I have:

<input type="checkbox" name="giustificaEntrata" value="1">

I want this element checked when I open the popup - How do I do that?

I also want the beta value selected when I open the popup

<select name="pippo">
    <option value="vuoto" selected>-</option>
    <option value="beta">beta</option>
</select>
ahren
  • 16,803
  • 5
  • 50
  • 70
  • 2
    I am not sure if this is an answer or a comment, but this answer: http://stackoverflow.com/a/5876747/185672 explains it perfectly. ( try using google/stackoverflow search function first ) – Phil Nov 18 '13 at 14:26

2 Answers2

1

The attr method changes an element attribute, which is the initial state. The prop value changes the element property, which is the current state.

To set the checked state, use the prop method:

$('input[name=giustificaEntrata]').prop('checked', true);'

To select an option, use the val method:

$('select[name=pippo]').val('beta');
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • what is the difference beetwhen: $('select[name=pippo]').val('beta') and $('select[name=pippo]').eq(1).prop('selected',true) – Emanuele Ugo Nov 18 '13 at 14:52
  • @EmanueleUgo: Well, one works, the other one not. :) It would be `$('select[name=pippo] option').eq(1).prop('selected',true);` for the second one to work. For a `select` without the `multiple` attribute, the result is the same. The difference is only how it's done. The result of `$('select[name=pippo] option')` is a jQuery object with all the option elements in the select, and you don't need all of them so that's a wasteful way to select one option. – Guffa Nov 18 '13 at 15:30
0

The checkbox checked property basically has two states. checked - true & checked - false.

From prop documentation, According to the W3C forms specification, the checked attribute is a boolean attribute.

Also, The checked attribute value does not change with the state of the checkbox, while the checked property does.

$('[name="giustificaEntrata"]').prop('checked',true);
Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56