Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

Manipulating Elements

We've already met the val() method. This method works great with practically all form elements. Yep, practically — setting a value this way won't work with <input type="radio">, you'll need a small workaround:

$("input[type=radio][name=sex][value=male]").prop("checked", true)
<label>
  <input type="radio" name="sex" value="male"/> Male
</label>
<label>
  <input type="radio" name="sex" value="female"/> Female
</label>

You could, of course, use the click() method to emulate selecting the desired option, but that would trigger all "click" event handlers, which is undesirable.

With <input type="checkbox"> it's a tiny bit simpler:

$("input[type=checkbox]").prop("checked", true)
<label>
  <input type="checkbox" name="remember"/> remember me
</label>

Checking the "checkedness" with a simple script:

$("input[type=checkbox]").prop("checked")

An alternative, slightly more visual way:

$("input[type=checkbox]").is(":checked")

We now know how to validate and submit a form via AJAX — all that's left is to deal with dynamically modifying the form. And we already have all the knowledge we need for that. For example, adding a dropdown:

What if we need to modify the dropdown?

Got it covered for every occasion:

And just like that, we've conquered the "terrible" forms. Maybe I'll add a few more real-life examples, but that'll be in future versions of this textbook :)

Last updated