Solved

JQuery - Set selected index of multiple <selects> with the same ID

Posted on 2015-02-20
8
84 Views
Last Modified: 2015-02-23
I have a form with rows of checkboxes and corresponding Selects.

E.G. Below shows the ID's of the form elements:

Checkbox  Select1  Select2  Select3  Select4
printer1     usage1  usage1  usage1  usage1
printer2     usage2
printer3     usage3  usage3  usage3  usage3
printer4     usage4
printer5     usage5  usage5  usage5  usage5

Sometimes there is only one 'usage[x]' <select> and other times there are 4.  My problem exists when I have 4.

I am trying to SelectIndex = 1 for the 'usage[x]' <select> when the corresponding 'printer[x]' box is checked.  Example, if 'printer3' is checked, the SelectedIndex of all 4 'usage3' becomes 1 and changes to 0 when unchecked.  In cases when there is only one 'usage[x]' select, it works fine, but when there are 4 it only changes the first one to SelectedIndex = 1.

In the cases where I have 4  'usage[x]' selects, how can I change the SelectedIndex=1 on all 4?

My code:

$("[name=printer]").change(function () {
	if ($(this).is(":checked") == false) {
	                 	$("#usage" + $(this).attr("id").replace("printer", "")).prop("selectedIndex",0);
		return;
	}
	$("#usage" + $(this).attr("id").replace("printer", "")).prop("selectedIndex",1);
})

Open in new window


Thanks,
Max
0
Comment
Question by:MaxwellTurner
  • 4
  • 3
8 Comments
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
Have a look at this fiddle. Should do what you need it to:

http://jsfiddle.net/ChrisStanyon/d8m4znzw/
0
 
LVL 52

Expert Comment

by:Scott Fell, EE MVE
Comment Utility
You may end up with other issues when you have multiple ID's.  Are you generating the code that produces the id?
0
 
LVL 1

Author Comment

by:MaxwellTurner
Comment Utility
@Chris:  Thanks for the example.  It essentially does what I am looking for, however I need the 'name' to remain the same on each row as I am generating  'printer' and 'usage' lists using name.  I can see what you did there ... still trying to figure a way I can frankenstien your code and mine together somehow ...

@Scott:  I am generating the code.  The form elements are within a coldfusion cfoutput query and the numerical parts of the id are a simple incremental (+1) counter within the cfoutput tags.  The output is a list of printers (the checkboxes) and below each printer is a list of consummables for that specific printer - one for mono printers and 4 for color printers.  The select boxes (usage) are labeled 1-99 with an actual value of 'the number selected-itemsku' which I strip apart later.

I am simply trying to add some validation to help ensure that if a user selects a checkbox, the related selects are forced to have a value, in this case a default value of 1 ... my users sometimes forget to choose the usages and this can cause problems.  I strip the lists down later to use the data and if a user forgets to select the usages on a printer, the usage list will be 1-4 items short.  I cannot have the all selects with a default of 1 because, I only need a value there if a printer has been selected.

Perhaps I am making this more difficult than I need to ... thought this would be a simple 5 minute task, but I fairly new to JQuery and it has become tougher thatn I thought it would be.

Will keep working on it ...

Max
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
You can still use my example - my jquery code will work with your elements as long as the checkbox names begin with printer and the select names begin with usage.

The reason I use an array syntax is because it makes processing the POST data a lot easier. You won't have to split strings to get the info. You can simply loop through the post array.

For example, if you name your checkboxes as printer[printer1], printer[printer2], printer[printer3] etc, and your dropdowns as usage[printer1][1], usage[printer1][2], usage[printer1][3], usage[printer2][1], usage[printer2][2] etc, then your POST data will something like this:

array (size=2)
  'printer' => 
    array (size=2)
      'printer1' => string 'yes' (length=3)
      'printer3' => string 'yes' (length=3)
  'usage' => 
    array (size=3)
      'printer1' => 
        array (size=3)
          1 => string '1' (length=1)
          2 => string '0' (length=1)
          3 => string '1' (length=1)
      'printer2' => 
        array (size=1)
          1 => string '0' (length=1)
      'printer3' => 
        array (size=3)
          1 => string '1' (length=1)
          2 => string '1' (length=1)
          3 => string '0' (length=1

Open in new window


You can now easily loop through $_POST['printer'] to see which printers were ticked, and through $_POST['usage'] to see which <select> options were chosen for each selected printer.
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 1

Author Comment

by:MaxwellTurner
Comment Utility
Hmmm okay, I must admit I'm not enirely understanding how to process the POST data as you have described, but I think I can figure that out.   In the meantime, I have incorporated the code as you have described, however there is one minor difference.  My usage selects are in a separate <tr> below the printer row ... how dan I make:

$(this).parents('tr')

refer to the row above instead of the same row?

Max
0
 
LVL 42

Accepted Solution

by:
Chris Stanyon earned 500 total points
Comment Utility
I don't use ColdFusion, so I can't help with that, but the $_POST data is a multi-dimensional array. Here's how you could do it with PHP if that helps:

// Loop through the selected printers
foreach ($_POST['printer'] as $printer => $selected):
	printf("Selected Printer: %s", $printer);
	
	// loop through the usage data for the selected printer
	foreach ($_POST['usage'][$printer] as $key => $value):
		printf("   Usage: %s = %s", $key, $value);
	endforeach;
endforeach

Open in new window


This would output something like:

Selected Printer: printer1
   Usage: 1 = 1
   Usage: 2 = 0
   Usage: 3 = 1
Selected Printer: printer2
   Usage: 1 = 1

Open in new window


You can tweak the <select> names to get a more meaningful output if needed

As for the jQuery selector, just get the next('tr'):

$('select[name^=usage]', $(this).parents('tr').next('tr')).prop("selectedIndex", usage);

Open in new window

0
 
LVL 1

Author Comment

by:MaxwellTurner
Comment Utility
Got it! I even was able to leave the names as 'printer' and 'usage'.  For this purpose it is much easier if I simply end up with 2 lists.

It was:

$('select[name^=usage]', $(this).parents('tr').next('tr')).prop("selectedIndex", usage);

that I was missing!

Thank you Chris!  Works perfectly!

Max
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
Glad I could help :)
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now