Adam Starrh Adam Starrh - 1 year ago 42
jQuery Question

Chaining jquery functions - Beginner

I am trying to set the name and ID of an element when a radio button is clicked on. To avoid duplicating the selector, I attempted to set it up like this:

$( "#selectOther" ).click(function() {
$( "[field=primaryInput]" ).attr('id', "modifiedId", function() {
$(this).attr('name', "modifiedName");
if ($(this).attr('visible') == "False") {
$(this).attr("visible", "True");

However, it isn't working. It seems that the ID is changed, but the Name is not, nor is the rest of the function executed. Could someone help me understand how to express this correctly?

Here's a JFiddle.

EDIT: In my final case I will have a couple of buttons that reveal the field if it is hidden, and others that will hide it if it is visible. That is why I am not using

Answer Source

See this fiddle:

$('input[type="radio"]').click(function() {
    .css('display', 'inline-block');

Number of points:

  1. You didn't set an external resource (namely jQuery) in your fiddle - so you wouldn't ever get jQuery functions to execute
  2. Use the data attribute for custom attributes. You can access them the way I have done or by selecting the $(element).data('field')

This example might help you understand how chaining works. One other piece of advise is that chaining only works if the method invoked next receives the same element the previous method returns. If it ever changes, you can use end() to get the previous state.