Solved

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

Posted on 2015-02-20
8
94 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 
LVL 43

Expert Comment

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

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

Expert Comment

by:Scott Fell, EE MVE
ID: 40623570
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
ID: 40626839
@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
Report: Liquid Web beats Amazon, Rackspace & More

A study by performance analyst firm Cloud Spectator finds that Liquid Web beats rivals Amazon, Rackspace and DigitalOcean when it comes to website and cloud application performance.

 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 40626994
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
 
LVL 1

Author Comment

by:MaxwellTurner
ID: 40627026
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 43

Accepted Solution

by:
Chris Stanyon earned 500 total points
ID: 40627088
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
ID: 40627139
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 43

Expert Comment

by:Chris Stanyon
ID: 40627141
Glad I could help :)
0

Featured Post

Major Incident Management Communications

Major incidents and IT service outages cost companies millions. Often the solution to minimizing damage is automated communication. Find out more in our Major Incident Management Communications infographic.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
jQuery element reference issue 2 40
JQuery Data Table Default Sort 2 34
Need help for active menu class depending of the page 4 30
How does this modal gets closed? 6 42
I have answered several questions lately that were solved utilizing the power of jQuery's AJAX functions, so I thought I would write an article demonstrating the ease of use. Why should I use jQuery as opposed to regular JavaScript? Now I know…
What is a Lightbox? A Lightbox is the effect you see when you click, for example, an image and the screen fades out and up pops the same image but in its full size dimensions. There are lots of Lightbox effects for jQuery. Problem is they are a…
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)
The viewer will learn the basics of jQuery including how to code hide show and toggles. 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…

752 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