selecting option in dynamcially generated select boxes when id is unknown - javascript

I am generating a html select boxes dynamically. The select boxes have a name:value pair of the number of total select boxes. That said, if I have 4 select boxes, then in each of the select box should have options like:
<select id="dynamic_id" >
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
</select>
. That I've accomplished already. Now I want option 1 to be selected for the first select box, option 2 to be selected for the second select box and so on.
(I am a complete noob and maintainig someone's code. So the code is pretty ugly but if you guys should need it...I will post it.)
EDIT
At the moment, abdulla's suggestion is working a bit but not fully. It always selects the first item only. Guys, this is a horrible code, but I think only it can help you understand mistakes I'm making:
var r_count=0;
$(document).ready(function(){
var newId; var tableName; var display_table;
$(".clickable").each(function(i,l){
$(l).click(function(){
var parentId = $(this).parents("div")[0].id;
var li = $(this).parents("li")[0];
var liIndex = $(li).parent().find("li").index(li);
newId = parentId + "_" + liIndex;
if(this.checked) {
display_table = $("#display_board");
var newtr = $(".data_table_template").clone();
tableName = $($(this).parents("table")[0]).find("th").text().trim();
var columnName = $(this).parent().text().trim();
newtr.attr("id",newId);
newtr.attr("class","");
newtr.show();
newtr.find("td").each(function(i,l){
if(i==0)
$(this).html(columnName)
else if(i==2)
$(this).html(tableName)
else if(i==3){
$(this).each(function(i,l){
$(this).find("#checkbox").attr("id", "chkbx_" + newId);
});
}
else if(i==4){
$(this).each(function(i,l){
//$(this).find("#select").html();
/* Generate new id for the table item dynamically*/
$(this).find("#select").attr("id", "sort_type_" + newId);
$(this).find(".sel1").attr("name", "sort_type_" + newId);
$(this).find("#checkbox").attr("id", "sort_type_" + newId);
});
}
else if(i==5)
$(this).each(function(m,l){
/* Generate new id for the table item dynamically*/
$(this).find("#select2").attr("id", "sort_order_" + newId);
$(this).find(".sel2").attr("name", "sort_order_" + newId);
});
});
display_table.append(newtr);
r_count++;
// addOption is from another jquery plugin
$(".sel2").addOption(r_count+1, r_count+1);
// as suggested in the answer
$('select').each(function (index, item) {
$(this).children('option:nth-child(' + (index +1) + ')').attr('selected', 'selected');
});
} else {
r_count--;
//$("#" + newId).find("#chkbx_"+newId).attr('checked','');
$("#" + newId).remove();
$(".sel2").addOption(r_count, r_count);
}
}
);
});
Only the select boxes in the 5th column are in consideration.

$('select').each(function(index, value) {
this.selectedIndex = index;
});

You could generate the select boxes with the option that you wanted having the attribute:
selected="true"

This also works, by setting the selected="selected" property on the children..
$('select').each(function (index, item) {
$(this).children('option:nth-child(' + (index +1) + ')').attr('selected', 'selected');
});

if i have understood correctly, i assume you have the following markup
<select id="dynamic_id" >
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
</select><br/>
<select id="dynamic_id2" >
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
</select><br/>
<select id="dynamic_id3" >
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
</select><br/>
<select id="dynamic_id4" >
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
</select>
you can try
$("select").each(function(index){
index=index+1;
$(this).find("option[value='"+index+"']").attr("selected","selected");
});
here is the fiddle http://jsfiddle.net/skyWJ/

$('select').each(function(index, value) {
$(this).val(index + 1).change();
});

Related

Switch based url redirection

I'm having a problem get this piece of code to work:
$(document).ready(function(){
$('#ButtonAluguel').click(function(){
{
var id = $(this).attr('name');
var str = "";
$("option:selected").each(function () {
switch(id=='Trololo'){
case true:
var option = $(this);
str += '?tid_1[]='+ option.attr('value');
break;
case false:
var option = $(this);
str += '?tid[]='+ option.attr('value');break;
}
});
window.location = "localhost/aluguel"+ str;
}});
});
I need it to keep adding stuff to "str" based on the name of a multiple select, identified above as id. Long story short, if the name of the select is "Trololo", id adds tid_1[], if not, it adds tid[] to the str. Any help is appreciated.
Edit:
The multiple select code is as follows(Forgot to put it in the first place, the question doesn't make much sense without it)
<form >
<select class="SelectTipoAluguel" multiple="true" data-placeholder="Tipo de Imóvel" style="width:200px;">
<option value="1">Aasdasdasd</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<select name="Trololo" class="SelectBairroAluguel" id="trololo" multiple="true" data-placeholder="Bairro" style="width:200px;">
<option value="1">Aadasd</option>
<option value="2">Basda</option>
<option value="3">Casda</option>
<option value="4">Dasda</option>
</select>
<input class="ButtonSubmitHome" id="ButtonAluguel" value="Pesquisar" >
</form>
To explain it more clearly, the user must fill the form and choose between the options, so when he clicks the "ButtonAluguel", every option from the select "SelectTipoAluguel" is added to the URL as tid[] and the ones from "SelectBairroAluguel" is added to the URL as tid_1[]
Code edited to reference updated question and OP's comments.
$(document).ready(function() {
var id;
var str = "";
$('#ButtonAluguel').click(function() {
var option = [];
$('select option:selected').each(function(i, selected) {
id = $(this).parent().attr('name');
option[i] = $(selected).val();
if (id == 'Trololo') {
str += '?tid_1[]=' + option[i];
} else {
str += '?tid[]=' + option[i];
}
});
var url = "localhost/aluguel" + str;
console.log(url);
//window.location = "localhost/aluguel" + str;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="SelectTipoAluguel" multiple="true" data-placeholder="Tipo de Imóvel" style="width:200px;">
<option value="1">Aasdasdasd</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<select name="Trololo" class="SelectBairroAluguel" id="trololo" multiple="true" data-placeholder="Bairro" style="width:200px;">
<option value="1">Aadasd</option>
<option value="2">Basda</option>
<option value="3">Casda</option>
<option value="4">Dasda</option>
</select>
<input class="ButtonSubmitHome" id="ButtonAluguel" value="Pesquisar">

Trigger a javascript function after select multiple option from <select> tag

I have a multi select tag is here. I like to call a function after select multiple option from select tag.
<select name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
If any body mark as duplicate please let me know the correct link. I search lots here and google also. but non of solution is good for my problem.
You can listen to change event in the same way as you do this with non-multiple select:
$("#cars").on('change', function()
{
var selectedItems = $(this).find("option:selected");
if (selectedItems.length <= 1)
{
$("#result").text("not multiple!");
return;
}
var text = "";
$.each(selectedItems, function() {
text += $(this).val() + " ";
});
$("#result").text(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="cars" name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<div id="result"></div>
Use .change instead like so :
$('select').change(function(e){
var length = $('option:selected', this).length;
if ( length > 1 ) {
alert('hey');
}
});
DEMO
You can do something like this with help of change() and blur() event handler
$('select').change(function() {
if ($('option:selected', this).length > 1) {
// set custom data attribute value as 1 when change event occurred and selected options are greater than 1
$(this).data('select', 1);
} else
//set value as zero in other case
$(this).data('select', 0);
}).blur(function() {
if ($(this).data('select')) {
// when focus out check custom attribute value
alert('selected more than one');
// code here
// call your function here
}
$(this).data('select', 0)
// set custom attribute value to 0
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
try this, it will call a function passing the newly selected value into functionToCall.
var values = [];
$('select').change(function(e){
var current = $(this).find('option:selected').map(function() {
return $(this).val();
});
var newValue = $(current).not(values).get();
values = current;
if(newValue.length)
functionToCall(newValue);
});
function functionToCall(value){
alert(value);
console.log(value);
}
Fiddle

Jquery: change value of a dropdown... when triggered through a delegate event

I have two dropdowns, and I want it so that, when the user changes the first dropdown, the second gets updated automatically to the same value. Due to some complicated reasons, I have to trigger the change via an on() delegate event. My code is like this:
<form>
<select id="destino_1">
<option value="268">AAA</option>
<option value="409">BBB</option>
<option value="570">CCC</option>
<option value="895">DDD</option>
<option value="943">Arena</option>
</select>
<select id="origen_2" class="origen">
<option value="268">AAA</option>
<option value="409">BBB</option>
<option value="570">CCC</option>
<option value="895">DDD</option>
<option value="943">Arena</option>
</select>
</form>
And my Javascript is this:
$("body").on('change',"#destino_1", function(){
$("#origen_2").trigger("cambiaOrigen");
});
$('body').on('cambiaOrigen', '.origen', function() {
var nombre=this.id;
var numero=parseInt(nombre.slice(-1));
//alert("Mooooo " + nombre);
if (numero > 1) {
var anterior = $("#destino_" + (numero - 1)).val();
this.find("option[value='" + anterior + "']").prop("selected", "selected").change();
//this.val(anterior);
}
});
I've created a fiddle at http://jsfiddle.net/w7c4o4cd/
As you can see, the event gets correctly triggered, the code gets the value of the first dropdown... but then I can't change the value of the second dropdown. I've tried both ways: with
this.find("option[value='" + anterior + "']").prop("selected", "selected").change();
And also with this.val(anterior);. Neither of them work. When executing in a browser, the error I get in the console is that this.find and this.val() are not functions... and yet, if you try to display this.id, it seems that this is referring correctly to the second dropdown, instead of to, say, body. (Also, if I try to display this, it says that it's an "HTML selectElement").
What's going on?
In your cambiaOrigen handler, this refers to a node not a jQuery object, what you would want is $(this) instead.
Also to set the selected option of a select tag you can simply set its value
this.value = anterior;
http://jsfiddle.net/mowglisanu/w7c4o4cd/2/
$("body").on('change',"#destino_1", function(){ $("#origen_2").trigger("cambiaOrigen");
});
$('body').on('cambiaOrigen', '.origen', function() {
var nombre=this.id;
var numero=parseInt(nombre.slice(-1));
//alert("Mooooo " + nombre);
if (numero > 1) {
var anterior = $("#destino_" + (numero - 1)).val();
//alert("Meeeept " + anterior);
//alert (this);
this.value = anterior;
//this.val(anterior);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form>
<select id="destino_1">
<option value="268">AAA</option><option value="409">BBB</option><option value="570">CCC</option><option value="895">DDD</option><option value="943">Arena</option>
</select>
<select id="origen_2" class="origen">
<option value="268">AAA</option><option value="409">BBB</option><option value="570">CCC</option><option value="895">DDD</option><option value="943">Arena</option>
</select>
</form>
Just change this line
this.find("option[value='" + anterior + "']").prop("selected", "selected").change();
to this
$(this).find("option[value='" + anterior + "']").prop("selected", "selected").change();
Just set the value of the section dropdown based on the value of the first like this.
$("body").on('change', "#destino_1", function () {
$('#origen_2').val($(this).val());
});
$("body").on('change', "#destino_1", function () {
$('#origen_2').val($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="destino_1">
<option value="268">AAA</option>
<option value="409">BBB</option>
<option value="570">CCC</option>
<option value="895">DDD</option>
<option value="943">Arena</option>
</select>
<select id="origen_2" class="origen">
<option value="268">AAA</option>
<option value="409">BBB</option>
<option value="570">CCC</option>
<option value="895">DDD</option>
<option value="943">Arena</option>
</select>
</form>

Remove a dropdown value that has been selected from another dropdown menu

I have searching the web for a while and still I cant find an answer, I have three drop-down menus on my site.
I use them for accepting user preferences so the user can control the output of results.
So I want to know if its possible for the value to be taken out of the other 2 dropdowns if its selected in one.
for example if the user selects movies in the first one it wont be in the others.
here is my dropdowns
<select id="pref1select">
<option value="P">Preference One</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref2select">
<option value="P">Preference Two</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref3select">
<option value="P">Preference Three</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
This will disable it, but not remove it.
Fiddle: http://jsfiddle.net/p2SFA/1/
HTML: (Added .preferenceSelect class) and jQuery:
$(document).ready(function() {
$(".preferenceSelect").change(function() {
// Get the selected value
var selected = $("option:selected", $(this)).val();
// Get the ID of this element
var thisID = $(this).prop("id");
// Reset so all values are showing:
$(".preferenceSelect option").each(function() {
$(this).prop("disabled", false);
});
$(".preferenceSelect").each(function() {
if ($(this).prop("id") != thisID) {
$("option[value='" + selected + "']", $(this)).prop("disabled", true);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<select id="pref1select" class="preferenceSelect">
<option value="P">Preference One</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref2select" class="preferenceSelect">
<option value="P">Preference Two</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref3select" class="preferenceSelect">
<option value="P">Preference Three</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
If you want it removed, you will probably have to make jQuery know what to insert when it has reset because a new choice is made :)
This should work for you:
$(document).ready(function() {
$(".preferenceSelect").change(function() {
// Get the selected value
var selected = $("option:selected", $(this)).val();
// Get the ID of this element
var thisID = $(this).attr("id");
// Reset so all values are showing:
$(".preferenceSelect option").each(function() {
$(this).show();
});
$(".preferenceSelect").each(function() {
if ($(this).attr("id") != thisID) {
$("option[value='" + selected + "']", $(this)).hide();
}
});
});
});`
You should try this:
$(".preferenceSelect").on("change", function () {
$(".preferenceSelect option").prop("disabled", false);
var selectPref = $("option:selected", $(this)).val();
var selectId = $(this).prop("id");
$(".preferenceSelect option").each(function () {
$(this).show();
});
$(".preferenceSelect").each(function () {
if ($(this).prop("id") != selectId) {
$("option[value='" + selectPref + "']", $(this)).prop("disabled", true);
}
});
});
This must be work for you.
I believe something like this would do the trick given the HTML above:
var $selects = $("select");
$selects.on("change", function(){
var value = this.value;
$("option[value='" + value +"']", $selects).prop("disabled", true);
});
var $selects = $("select");
$selects.on("change", function(){
var value = this.value;
$("option[value='" + value +"']", $selects).prop("disabled", true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="pref1select">
<option value="P">Preference One</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref2select">
<option value="P">Preference Two</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref3select">
<option value="P">Preference Three</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
This disables the duplicate options, but it's an easy change to remove them as well. You'll run into a slight issue, though, since the "Preference #" options all have the same value. I would recommend either making these optgroup labels or removing the values entirely and marking them as disabled from the start...since you shouldn't be able to click them in the first place. You can find a bit more on option labels, and separators answered here.
Example
Please try the following which is working fine with no issue. I am also marking the selected option as disable instead of hiding from the other dropdowns.
$( function() {
courC();
});
function courC(){
var previous;
$(".pSel").on('focus', function () {
previous = this.value;
}).change(function() {
var selected = $("option:selected", $(this)).val();
var thisID = $(this).attr("id");
$(".pSel option").each(function() {
$(this).show();
});
$(".pSel").each(function() {
var otid=$(this).attr("id");
if (otid != thisID) {
if( $('#'+otid).val() == selected){ $('#'+otid).val(''); } // this is required when you are viewing data once again after the form submission
$("option[value='" + selected + "']", $(this)).attr("disabled", true);
}
$("option[value='" + previous + "']", $(this) ).attr("disabled", false); // this will help to reset the previously selected option from all dropdown
});
previous = $('#'+thisID).val();
});
}

coding onchange event

hello
i need to load page based on the results of dropdown box. for example in my code i have value="userlog". if this selected it will load userlog.php and remove itself so that only userlog.php is being used. thanks
<select onchange="updatePage(this.value)">
<option value="">Select a report</option>
<option value="userlog">User Logs</option>
<option value="actionlog">Action Logs</option>
</select>
<select id="select_page">
<option value="">Select a report</option>
<option value="userlog">User Logs</option>
<option value="actionlog">Action Logs</option>
</select>
$('#select_page').change(function() {
var $el = $(this);
if($el.val() != '') {
$('#page').load($el.val()+'.php');
$el.find('option:selected').remove();
}
});
On change event you will get the selected options value. Using this value you can decide what you want to do.
something like this :
$(document).ready(function() {
$("select option ").each(function() {
if (location.href.indexOf($(this).val()) >= 0) {
$(this).remove();
}
});
$('select').change(function() {
var obj = $(this);
location.href = obj.val() + ".php";
});
});

Categories