Select the option dynamically using Jquery - javascript

I am designing a dynamic HTML for Select Option like below:
item += "<td class='ddl' style='width:40%;'>";
item += "<select>"
item += " <option id='list' name='selector' value=" + select + ">" + select + "</option>";
for (var l = 0; l < array.length; l++) {
item += " <option class='ddl' value=" + array[l] + ">" + array[l] + "</option>";
}
item += "</select>";
if ("One"!= '') {
$('#list').val("One");
}
item += "</td>";
The above code creates a dynamic HTML like below:
<select disabled="">
<option select="" value="Please" name="selector" id="list">Please Select</option>
<option value="One" class="ddl">One</option>
<option value="Two" class="ddl">Two</option>
</select>
I want to set the value of the Select to "One" dynamically.
NOTE: The code is not inside document.ready, as I cant keep the code inside ready().
Might be I am assigning the value to the Select before it is revdered on the page. Please suggest me.

You need to call the javaScript to select the value after the dropdown(select) is added to the page. For example if the html is
<div id="myContainer" />
Then the javascript should be like
var item = "";
//Insert your code to create item
item +="<select id='mySelect'>";
item +='<option select="" value="Please" name="selector" id="list">Please Select</option>';
item +='<option value="One" class="ddl">One</option> ';
item +='<option value="Two" class="ddl">Two</option>';
item +='</select>';
$('#myContainer').append(item); //Add to html
//Now the id "mySelect" is available
$('#mySelect').val('One')
I've added a jsFiddle to demonstrate this at http://jsfiddle.net/taleebanwar/n9vCb/

You could also set a selected attribute on the corresponding option tag as you create the select dynamically.

If you are using jQuery then why don't you utilize the library for creating the select, for example, using something like this (Example):
var numbers = ['one', 'two', 'three', 'four', 'five'];
var select = $('<select/>', {id:'list', name:'selector'});
$.each(numbers, function(key, value) {
var text = value[0].toUpperCase() + value.substr(1);
var option = $("<option/>", { class:'ddl', value: value, text: text });
select.append(option);
});
select.val('two').appendTo('body');
I've appended the select into body but you may append it into a td and you can achieve it, give it a try, create the td same way and insert the select in the td and then insert the td in the table. Also you may check this answer.

Related

Reset name attribute array indexes, dynamically add remove rows

I have to post data via ajax and need the name attribute array indexes to reset.
For example:
1st row:
<select data-placeholder="Colours" class="colours chosen-select"
multiple tabindex="4" name="colours[0][]">
<option value="">Red</option>
<option value="">Orange</option>
</select>
2nd Row dynamically added:
<select data-placeholder="Colours" class="colours chosen-select"
multiple tabindex="4" name="colours[1][]">
<option value="">Red</option>
<option value="">Orange</option>
</select>
The name colours array must increment by 1 everytime I add, as well as reset the values when I remove.
I have looked around but not found any solution.
Here is what I have:
Adding:
var tbl = $("#service");
$("#addRowBtn").click(function () {
var count = $('#rowCount tr').length;
$("<tr>" +
"<td>" +
"<select data-placeholder=\"Colours\" class=\"colours chosen-select\"
multiple tabindex=\"4\"\ name=\"colours[" +
count +
"][]\">" +
"<option value=\"\">Red</option>" +
"<option value=\"\">Orange</option>" +
"</select></td>" +
"<td><i style=\"color:#d64830\" class=\"delRowBtn fa fa-minus-
circle\"></i></td></tr>").appendTo(tbl);
Deleting a row:
$(document.body).delegate(".delRowBtn", "click", function () {
$(this).closest("tr").remove();
});
I have added var count to increment the indexes, but I'm not able to reset the values when removing.
Please help!
You can try to cycle all select of your table and change the attribute "name" of each select everytime you delete an item.
$('#rowCount tr td select').each(function(idx, item){
$(item).attr("name", "colours[" + idx + "][]")
});
update
like suggest #ChayimFriedman the cool version of previous suggestion
$('#rowCount select').attr('name', function(idx) { return "colours[" + idx + "][]"; });

How to programmatically select an option inside a variable using jQuery

Let say I have this variable html which contain these select options:
var html = '<select>'+
'<option value="10">10</option>'+
'<option value="20">20</option>'+
'</select>';
How can I programmatically select an option which is inside the html variable so when I append them to somewhere, for example
$(this).children('div').append(html);
it will become like this:
<div> <!-- children div of the current scope -->
<select>
<option value="10" selected>10</option>
<option value="20">20</option>
</select>
</div>
How is it possible?
edit: the variable contents is generated from remote locations, and I must change the value locally before it is being appended into a div. Hence, the question.
edit 2: sorry for the confusion, question has been updated with my real situation.
You can cast the HTML into a jQuery element and select the value at index 0. Then you can add it to the DOM.
Here is a simple jQuery plugin to select an option by index.
(function($) {
$.fn.selectOptionByIndex = function(index) {
this.find('option:eq(' + index + ')').prop('selected', true);
return this;
};
$.fn.selectOptionByValue = function(value) {
return this.val(value);
};
$.fn.selectOptionByText = function(text) {
this.find('option').each(function() {
$(this).attr('selected', $(this).text() == text);
});
return this;
};
})(jQuery);
var $html = $([
'<select>',
'<option value="10">10</option>',
'<option value="20">20</option>',
'</select>'
].join(''));
$('#select-handle').append($html.selectOptionByIndex(0));
// or
$html.selectOptionByValue(10);
// or
$html.selectOptionByText('10');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="select-handle"></div>
By default, the first option will be selected - if you want to do on any other set it so using the index as soon as the select is appended:
$('#select_handle option:eq(1)').prop('selected', true)
(this selects the second option)
See demo below:
var html = '<select>'+
'<option value="10">10</option>'+
'<option value="20">20</option>'+
'</select>';
$('#select_handle').append(html);
$('#select_handle option:eq(1)').prop('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="select_handle"></div>
You could try simply setting the value of the drop-down to the one you wish to 'select' - like
$("#select_handle select").val( a_value );
For example, if a_value is 30 it will add the needed HTML to the DOM node. This would be my take:
$(function() {
var html = '<select>' +
'<option value="10">10</option>' +
'<option value="20">20</option>' +
'<option value="30">30</option>' +
'<option value="40">40</option>' +
'<option value="50">50</option>' +
'</select>';
// set a value; must match a 'value' from the select or it will be ignored
var a_value = 30;
// append select HTML
$('#select_handle').append(html);
// set a value; must match a 'value' from the select or it will be ignored
$("#select_handle select").val(a_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>select added below</h2>
<div id="select_handle">
</div>
selected="selected" will work
var html = '<select>'+
'<option value="10">10</option>'+
'<option value="20" selected="selected">20</option>'+
'</select>';
$('#select_handle').append(html);
You can do this in jQuery using the .attr() function and nth pseudo-selector.
Like so:
$("option:nth-child(1)").attr("selected", "");
Hope it helps! :-)
after the append, try $('#select_handle select').val("10"); or 20 or whatever value you want to select

create a select dropdown option with values and text according to the specified data attribute

so below is my snippet. What I want is to create a select dropdown option base from the data attribute (data-select-text and data-select-values) of the currently clicked button, so below is a working snippet except for getting the data-select-values which is the problem because i dont know how to loop it along with the data-select-text so that the result of each select option will have values and text base from the split values of the data-select-text and data-select-values attribute, any ideas, help, suggestions, recommendations?
NOTE: currently, I could only able to use the attribute data-select-text as a select options values and text.
$(document).ready(function(){
$(document).on("click", "button", function(){
if($(this).attr("data-input-type").toLowerCase() === "select"){
var classList = $(this).attr('data-select-text').split(/\s+/);
var field = '<select>';
$.each(classList, function(index, item) {
field += '<option value="' + item.replace(/%/g, ' ') + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-input-type="select" data-select-text="select%1 select%2 select%3" data-select-values="1 2 3">Create a select dropdown option</button>
You could create an array for the values, the same as so did for the text.
Make sure that the order in both data-select-text and data-select-values is the same. Then you can use the index in your $.each loop:
$(document).ready(function(){
$(document).on("click", "button", function(){
var elem = $(this);
if( elem.attr("data-input-type").toLowerCase() === "select" ){
var classList = elem.data('select-text').split(/\s+/),
valueList = elem.data('select-values').split(/\s+/),
field = '<select>';
$.each(classList, function(index, item) {
field += '<option value="' + valueList[index].replace(/%/g, ' ') + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-input-type="select" data-select-text="select%1 select%2 select%3" data-select-values="1 2 3">Create a select dropdown option</button>
The result will be:
<select>
<option value="1">select 1</option>
<option value="2">select 2</option>
<option value="3">select 3</option>
</select>
Here is one way to do it, if I understand correctly. This code does not take into account different text or value lengths. It expects that the text length of options created is always equal to the values length being used.
$(document).ready(function () {
$(document).on("click", "button", function () {
if ($(this).attr("data-input-type").toLowerCase() === "select") {
var classList = $(this).attr('data-select-text').split(/\s+/);
var valueList = $(this).attr('data-select-values').split(' ');
var field = '<select>';
$.each(classList, function (index, item) {
field += '<option value="' + valueList[index] + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
Fiddle: http://jsfiddle.net/32qt0vn8/

Get Select Value and Option from Specific Table Row and Column with Javascript or JQuery

I have a table that has rows appended to it. Each row has a select in column 2 {0, 1, [2]}. I am trying to get the text/value/option of the select using JavaScript or JQuery. This seems like it should be something easy but for the life of me I cannot figure out a way to get the select element in the selected row & column. Any help would be greatly appreciated.
Here is my table.
<div id="table_container">
<table id="computer_table" class="service_table">
<thead id="header_container">
<th class="table_header">COMPUTER NAME</th>
<th class="table_header">LIVE/HIDE</th>
<th class="table_header">MODE</th>
<th class="table_header">RUN</th>
</thead>
<tbody id="table_body">
</tbody>
</table>
</div>
Here is my JavaScript that adds rows to the table. Rows contain a select in column 2.
row = $('<tr class="row_white"><td class="tb_pc_name">' + value.pc_name + '</td><td class="tb_live_hide">LIVE</td><td class="tb_mode">' +
'<select id="select_mode" class="select_dropdown">' +
'<option value="0">0 - DEFAULT</option>' +
'<option value="1">1 - CLEAN UP</option>' +
'<option value="2">2 - SIGN IN</option>' +
'<option value="3">3 - SIGN OUT</option>' +
'<option value="4">4 - UPDATE IPSW</option>' +
'<option value="5">5 - OPEN DMG DIRECTORY</option>' +
'</select></td>' +
'<td class="tb_btn"><button type="button" id="btn_run">RUN</button></td></tr>');
$("#computer_table").append(row);
After all rows have been appended, the user can make a selection from the select. There is a button in column 3 that when clicked should show an alert with the select option and value of the select on the same row. The code below should show the selected option and/or value of the select in the row of the cell that is clicked. I can get the row and column but cannot get the value of the select.
$("#computer_table td").click(function() {
var table = document.getElementById('computer_table');
var column_num = parseInt( $(this).index() );
var row_num = parseInt( $(this).parent().index() );
alert('test');
/*Error here.*******************************************************************************************/
var combo = table.rows[row_num + 1].cells[2].getElementById('select_mode');
//$("#select_mode option:contains("?").attr('selected', 'selected');
alert(combo.value);
});
If you changed your buttons to use a class rather than an id they could be triggered with this:
$("#computer_table").on("click", "button.btn_run", function(e) {
alert($(this).parent().prev().children().find(":selected").text());
});
First of all there is something wrong with youre code that add the row. Every ID must be unique and it's not the case. Try using a counter (or something else) to avoid that like this:
var numberRowAdded = 0;
row = $('<tr class="row_white"><td class="tb_pc_name">' + value.pc_name + '</td><td class="tb_live_hide">LIVE</td><td class="tb_mode">' +
'<select id="select_mode'+ numberRowAdded +'" class="select_dropdown">' +
'<option value="0">0 - DEFAULT</option>' +
'<option value="1">1 - CLEAN UP</option>' +
'<option value="2">2 - SIGN IN</option>' +
'<option value="3">3 - SIGN OUT</option>' +
'<option value="4">4 - UPDATE IPSW</option>' +
'<option value="5">5 - OPEN DMG DIRECTORY</option>' +
'</select></td>' +
'<td class="tb_btn"><button type="button" id="btn_run'+ numberRowAdded +'">RUN</button></td></tr>');
$("#computer_table").append(row);
numberRowAdded++;
Then to select what you want :
$("#computer_table td").click(function() {
alert($(this).find(".select_dropdown").val());
});
Hope this help.
try passing in the ID onClick:
$("#computer_table td").click(function(this.id){ }
Just make sure all your cells have an ID.
Here is W3 example on enclosures and encapsulation. This is useful for giving all your elements a different ID. W3 encapsulation example
Adding elements with eventlisteners attached, and passing in a unique id!!
*Note: this is not an exact fix for your code. This should however aid you in understanding.
/*use this function to create unique id's*/
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
/*grab your table*/
var table =document.getElementById("computer_table");
/* create an element, set it's attributes*/
var newRow = document.createElement("th");
newRow.setAttribute("class", "table_header");
newRow.setAttribute("id", "table_header"+add());
/*add the event listener*/
newRow.addEventListener("click",function(this.id){ /* YOUR CODE HERE */ });
/*append to your table*/
table.appendChild(newRow);

How to remove all dropdown option and replace new option by only NAME attibute given?

need some help for jquery.
How can i remove all dropdown option and replace new option?
Note : Only Name attribute used, No ID attribute used in select tag.
<tr id="payment_currency_tr">
<TD class="prompt">
Payment currency*
</TD>
<TD class="formdata">
<SELECT name="payment_currency" onchange="" style="" > <!-- to clear this option and replace to SGD option only.
<OPTION value="">
<OPTION VALUE="USD" >USD
<OPTION SELECTED SELECTED VALUE="CHF" >CHF
<OPTION VALUE="SGD" >SGD
</SELECT>
</TD>
</tr>
I try below script but not work
1)
msg = 'SGD';
js_option = '<option value="' + msg + '">' + msg + '</option>';
jQuery("#payment_currency_tr")
.find('option')
.remove()
.end()
.append(js_option)
.val(msg)
2)
msg = 'SGD';
Var d = document.getElementsByName('payment_currency')[0];
d.options[0].option = msg;
d.options[0].value = msg;
I know there is a way to change by using ID attibute but too bad i can't used it due to the table structure is generated via some cfm custom tag and unable to modify
document.getElementById("payment_currency").options.length = 0;
jQuery("#payment_currency").children().end().append(js_option);
Try this simply,
msg = 'SGD';
js_option = '<option value="' + msg + '">' + msg + '</option>';
$('select[name="payment_currency"]').html(js_option)//set new html,replace previous options
.val(msg); // sel msg as selected option
Live Demo
or you can try
jQuery("#payment_currency_tr").find('select')// find drop down
.html(js_option)
.val(msg);
Another Demo

Categories

Resources