Example using attr() - javascript

Following this question - Extending Clone Table Rows functionality - changing row ID
The code - http://jsfiddle.net/EwQUW/58/
I want to update the attr. Please check the code and I have included comments to see what I am talking about.
EDIT
<table id="table">
<tbody>
<tr>
<td>
<select name="make[]" id="make" onchange="change(this,'model')">
<option value="" selected=“selected”> Please Select </option>
<option value=Ford> Ford</option>
<option value=Nissan> Nissan</option>
<option value=Volvo> Volvo</option>
<option value=BMW> BMW</option>
</select>
</td>
<td>
<select name="model[]" id="model" onchange="change(this,'make')">
<option value="" selected=“selected”> Please Select </option>
<option value=Ford> Fiesta</option>
<option value=Nissan> Mirca</option>
<option value=Volvo> s60</option>
<option value=BMW> M3</option>
</select>
</td>
<td>
<input id="country" name="country[]"/>
</td>
<td>
<input id="city" name="city[]" />
</td>
</tr>
</tbody>
</table>
<button id="add">Add</button>
Javascript
function change(fld,id) {
var opt = fld.selectedIndex;
if (fld[opt].value != ' ') {
var sel = document.getElementById(id);
for (var i = sel.options.length -1; i > -1; i--) {
if (fld[opt].value == sel[i].value) sel[i].selected = true;
}
}
}
When I add a new row, I want the ID, NAME and onchange to be updated with a count or length as you put.
As ID are updated and onchange to id=make to id=make2 so the onchange still works
EDIT AGAIN
Actually names will be an array. So only IDS and Onchange needs updating depending on number of rows

The first means I've come up with is:
function change(fld, id) {
var opt = fld.selectedIndex;
if (fld[opt].value != ' ') {
var sel = document.getElementById(id);
for (var i = sel.options.length - 1; i > -1; i--) {
if (fld[opt].value == sel[i].value) sel[i].selected = true;
}
}
}
$('select').change( // moving away from intrusive in-line JavaScript
function() {
var changeTarget; // used to determine which select to change
if (this.id == 'make') {
changeTarget = 'model';
}
else {
changeTarget = 'make';
}
change(this,changeTarget);
});
$('#add').click(
function() {
$('#table tbody tr:last').clone(true).appendTo($('#table')).find('input,select').each(
function() {
var attr = this.id.replace(/\d/, ''); // gets the text of the id attribute
var length = $('#table tbody tr').length; // finds what number the new attributes should be
if ($(this).is('input')){ // select elements don't need their name to be changed
$(this).attr({
'id': attr + length,
'name': attr + length
});
}
else if ($(this).is('select')){
$(this).attr('id',attr + length);
}
});
});​
JS Fiddle demo.
Edited to remove the hard-coded 'make'/'model' choice in the select change() event-handler to the following:
$('select').change(
function() {
var changeTarget = $(this)
.closest('tr')
.find($('select'))
.not($(this))
.attr('id');
change(this,changeTarget);
});
JS Fiddle demo.

Related

How to display an object of objects without repetitions on the site [duplicate]

I have a table in which first row is a label and drodown for selecting number of spaces.
based on the number selected that much number of rows and inside each row another table with input fields will come. everithing is ok in first time.but when i reselect the number from dropdown the number of rows append to the previous one. i want to replace the previous inner tables. how to do this.
this is my html code
<table border="1" style="border-style:dotted" width="100%" id="table_booking">
<tr>
<td>
<label > Number Of Spaces</label>
</td>
<td>
<select id="dropdown" class="" name="spaces" onchange="addForm(this.value)">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
</tr>
<table border="1" style="background-color:gray" width="100%" id="table_form">
</table>
</table>
this is the script
<script type="text/javascript">
function addForm(space)
{ var val=space;
document.getElementById('dropdown').value =val;
var doc=document.getElementById('table_booking');
for(var i=0;i<val;i++)
doc.innerHTML += '<tr><td><table width="100%" id="table_form"><tr><td><form><label>Name </label><input type="text"></form></td></tr></table></td></tr>';
}
</script>
Before appending, just flush the existing innerHTML like
doc.innerHTML = '';
Then append it,
for(var i=0;i<val;i++)
doc.innerHTML += '<tr><td><table width="100%" id="table_form"><tr><td><form><label>Name </label><input type="text"></form></td></tr></table></td></tr>';
Updates: Looking through your comments in other answers, I have devised the following approach,
function addForm(space) {
var val = space;
var doc = document.getElementById('table_booking').getElementsByTagName('tbody')[0];
// Remove nodes whenever we append new nodes to the tbody (RESET)
if (doc.getElementsByTagName('tr').length > 1) {
var len = doc.getElementsByTagName('tr').length;
for (i = (len - 1); i >= 1; i--) {
doc.getElementsByTagName('tr')[i].remove();
}
}
// Based on the value selected, new rows will be appended to the tbody
for (var i = 1; i <= val; i++) {
t = doc;
r = t.insertRow(i);
c = r.insertCell(0);
c.innerHTML = "<form><label>Name </label><input type='text'></form>";
doc.appendChild(r);
}
}
JSFiddle

How to change the content for each option of select element with Javascript or jQuery

My task here is to change the content in the table whenever the select's options change.
The code below is my solution but I don't think that is good at all. What if when the options have more than 3 options... this might lead me to modify lots of in the if else condition. Thus, if you have others solution, please let me know that.
Might I set id="approve_2" as show default with my edited JSFIDDLE?
Demo
HTML:
<table>
<tr>
<td>
<select id="select_vehicle">
<option value="company_vehicle">Company Vehicle</option>
<option value="hiring_vehicle">Hiring Vehicle</option>
<option value="taxi">Taxi</option>
</select>
</td>
</tr>
<tr id="company_vehicle">
<td>Company Vehicle</td>
</tr>
<tr id="hiring_vehicle">
<td>Hiring Vehicle</td>
</tr>
<tr id="taxi">
<td>Taxi</td>
</tr>
</table>
Javascript:
var select_vehicle = $("#select_vehicle");
// Set selected item
var set_selected_item = $(select_vehicle).val("company_vehicle");
// Hide options "Hiring Vehicle" & "Taxi"
var company_vehicle = $("#company_vehicle"); // Get id "Company Vehicle"
var hiring_vehicle = $("#hiring_vehicle"); // Get id "Hiring Vehicle"
hiring_vehicle.hide();
var taxi = $("#taxi"); // Get id "Taxi"
taxi.hide();
$(select_vehicle).on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
if (valueSelected == "company_vehicle") {
company_vehicle.show();
hiring_vehicle.hide();
taxi.hide();
} else if (valueSelected == "hiring_vehicle") {
company_vehicle.hide();
hiring_vehicle.show();
taxi.hide();
} else {
company_vehicle.hide();
hiring_vehicle.hide();
taxi.show();
}
});
JSFIDDLE: http://jsfiddle.net/huydq91/7us66/3/
You can shorten your code without repetition like this:
$('table tr:gt(0)').hide();
$('#select_vehicle').change(function() {
var val = $(this).val();
$('#'+val).show().siblings('tr').not(':first').hide();
}).change();
Updated Fiddle

jquery: obtain select inside a table row

I have a table row which looks like
the HTML looks like
When the user changes the value of the Name field I pass the "select" to nameDropChanged function. After obtaining a reference to select I want to change the value of Number of Coupons select box. How can I obtain a reference to it using Jquery? Also there will be many such exact rows in the table.
Update : Here is the dummy HTML code and jsfiddle link
<table id="competitors_table" width="100%" style="border-bottom: #000000 solid 1px;">
<tbody>
<tr>
<td>Name:<select name="CompetitorIDs_Setting_[]" onchange="nameDropDownChanged(this);">
<option value="0">N/A</option><optgroup label="Similar Stores"></optgroup>
<optgroup label="Other Stores">
<option value="1">flipkart</option>
<option value="2">bigshoebazaar</option>
<option value="160">presto</option>
<option value="3">fabindia</option>
<option value="4">fashnvia</option>
</td>
<td>
<select name="Position_Setting_[]" onchange="dropDownChanged(this);">
<option value="1000">Top</option>
<option value="1001">Middle</option>
<option value="1002">Bottom</option>
<option value="">Enter Position</option>
</select>
<input type="text" name="PositionNumber_Setting_[]" size="3" style="display: none;">
</td>
<td>Number of Coupons:<select id="numberOfCoupons_Setting_[]"></select></td>
</tr>
</tbody>
</table>
Javascript code
function nameDropDownChanged(select)
{
var selectedIndex = select.selectedIndex;
var WebsiteName = select.options[selectedIndex].innerHTML;
var couponCount = <?php if(!empty($couponCount)){ echo json_encode($couponCount); }?>;
if(Object.keys(couponCount).length > 0)
{
var numberOfCoupons = couponCount[WebsiteName];
var numberOfCouponsDropDown = document.getElementById('numberOfCouponsSelect');
$("#numberOfCouponsSelect").empty();
if(numberOfCoupons > 0)
{
for(var i=1; i <= numberOfCoupons; i++)
{
var option = document.createElement('option');
option.value = i;
option.innerHTML = i;
numberOfCouponsDropDown.appendChild(option);
}
}
else
{
var option = document.createElement('option');
option.value=1;
option.innerHTML = "No Active Coupons";
numberOfCouponsDropDown.appendChild(option);
}
}
}
inside the nameDropChanged function ..
// considering 'parameter' is the variable to be passed as a parameter to nameDropChanged function
$numberSelect = $(parameter).parent().nextAll(':last').children('select');
// $numberSelect is now containing a reference to the numberOfCoupons_Setting_[ select]
You can do something like this
$('#Selector_ID1, #Selector_ID2, #Selector_ID3, ...').change(function() {
var parent = $(this).parents("tr");
var elm = $("td:last-child", parent).children("select");
//Do your operation with last Select Element here.
});
This helps in two ways
You need not to know exact parents and children, but just reverse
track for parent which is TR in first case and then last SELECT in
the parent.
In a single go you can handle multiple rows. You can
also use class selector here.

Convert html select option list to radio buttons

I have a html page which works with select/option and I want to convert this feature to input type=radio (list to radio butons).
Actually i have a list of selects like this:
<select name="DEC-51537a4b580452b9e145b75c-A">
<option selected="" value="OK">OK</option>
<option value="NOK">NOK</option>
</select>
<select name="DEC-51537a4b58045459e145b75c-R">
<option selected="" value="OK">OK</option>
<option value="NOK">NOK</option>
</select>
<select name="DEC-51537a88880452b9e145b75c-A">
<option selected="" value="OK">OK</option>
<option value="NOK">NOK</option>
</select>
The user select the value that he want and click on a button.The button call a javascript which get the result for each "DEC-".
For each select which start with "DEC-", I retrieve :
- dec-number (51537a88880452b9e145b75c for example)
- original dec value (A or R)
- and i get select.value in order to retrieve the dec value select by the user
If i want to convert select to input type=radio, first of all I have change select to this:
<input name="DEC-51537a4b580452b9e145b75c-A" type="radio" checked value="A">A
<input name="DEC-51537a4b580452b9e145b75c-A" type="radio" value="R">R
And here the javascript function which works with select but not radio buttons:
var elements = $doc.getElementsByTagName('select');
var sel;
for(var i=0; i<elements.length; i++){
sel = elements[i];
if(sel.name.indexOf('DEC-') === 0){
var selName = sel.name.split('-');
var oid = selName[1];
var originalDecision = selName[2];
var supervisorDecision = sel.value;
decisions++;
if(originalDecision == supervisorDecision) {
rightDecisions++;
} else {
wrongDecisions++;
if(originalDecision == "ACCEPTED") {
originalDecision="<h3 class='green'>ACCEPTED</h3>";
} else if(originalDecision == "REFUSED") {
originalDecision="<h3 class='red'>REFUSED</h3>";
}
if(supervisorDecision == "ACCEPTED") {
supervisorDecision="<h3 class='green'>ACCEPTED</h3>";
} else if(supervisorDecision == "REFUSED") {
supervisorDecision="<h3 class='red'>REFUSED</h3>";
}
var content = $doc.getElementById(oid).innerHTML;
wrongDecisionsTab += "<tr><td>" + content + "</td><td>"
+ originalDecision + "</td><td><h3>" + supervisorDecision + "</h3></td></tr>";
}
}
}
I need the same things but with radio buttons, so i have tried to change:
var elements = $doc.getElementsByTagName('input');
but it's not sufficient.
What i'm missing?

check options in multiple select boxes

I'm trying to find a way to check my options in different select boxes (total: 4).
The boxes include the same data in value/text.
How do I avoid that the option select is the same? (I use it for an sorting feature).
And how can i integrate it in the current jquery script. (I use ajax-post to parse data).
This is how it should not be:
Select one:
<ul>
<li class="move-img">
<select style="width:150px;"id="modul1" onchange="$.modules.options(this,1);">
<option value="0"></option>
<option value="1">name</option>
<option value="2">name2</option>
</select>
</li>
Select two
<ul>
<li class="move-img">
<select style="width:150px;"id="modul2" onchange="$.modules.options(this,2);">
<option value="0"></option>
<option value="1">name</option>
<option value="2">name2</option>
</select>
</li>
jQuery
$.modules = {
/* Get price for option-modules */
options: function(module_id,show_divid){
var modul = $(module_id).val();
if(modul != 0){
//show price
$("#showprice"+show_divid).html('<div class="ajax_loader left"></div>').fadeTo(300,0.25,function(){
var $show_price = $(this); // div tag
$.post('/ajax/modules/get_prices/',{check_data:'send_data',get_module_prices_id:modul},function(data){
$show_price.fadeTo(200,100,function(){
$show_price.html(data.module_price);
});
},'json');
});
}
}
}
I wonder whether this is what you are after: http://jsfiddle.net/william/K7nTr/.
It checks whether the value has already been selected. If it has, revert to the first value and alert the user.
$.modules = {
/* Get price for option-modules */
options: function(module_id, show_divid) {
var modul = $(module_id).val();
if (modul != 0) {
var selector = ".move-img option:selected[value=" + modul + "]";
if ($(selector).length > 1) { // see if this value has been selected elsewhere
alert('The value has been selected. Try again');
$('option:eq(0)', module_id).attr('selected', 'selected');
return;
}
//show price
$("#showprice" + show_divid).html('<div class="ajax_loader left"></div>').fadeTo(300, 0.25, function() {
var $show_price = $(this); // div tag
$.post('/ajax/modules/get_prices/', {
check_data: 'send_data',
get_module_prices_id: modul
}, function(data) {
$show_price.fadeTo(200, 100, function() {
$show_price.html(data.module_price);
});
}, 'json');
});
}
}
}
In onchange="$.modules.options('modul1',1);" you dont have to pass modul1, you can just pass this which will point to the changing select box. This applies to both the select boxes. You have few js error in your code, try this.
$.modules = {
/* Get price for option-modules */
options: function(module_id,show_divid){
var modul = $(module_id).val();
if(modul != 0){
//show price
$("#showprice"+show_divid).html('<div class="ajax_loader left"></div>').fadeTo(300,0.25,function(){
var $show_price = $(this); // div tag
$.post('/ajax/modules/get_prices/',{check_data:'send_data',get_module_prices_id:modul},function(data){
$show_price.fadeTo(200,100,function(){
$show_price.html(data.module_price);
});
},'json');
});
}
}
I'm not sure I understand. in html, replace the onChange
onchange="$.modules.options(this);"
in jquery, replace:
options: function(module){
var modul = $("option:selected", module).val();
and replace too
if(modul.length == 0);
else{
by
if( modul.length > 0) {
try this
var inputs = document.getElementsByTagName("input"); //or document.forms[0].elements;
var cbs = []; //will contain all checkboxes
var checked = []; //will contain all checked checkboxes
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
cbs.push(inputs[i]);
if (inputs[i].checked) {
checked.push(inputs[i]);
}
}
}
var nbCbs = cbs.length; //number of checkboxes
var nbChecked = checked.length; //number of checked checkboxes
for(var i=0;i<checked.length;i++)
{
if(checked[i].value=checked[i+1].value)
{
alert('Not allowed');
}
}
Not sure if i got you right here.
But my following example allows each option to be selected only once.
<script language="javascript" type="text/javascript">
var ValidateOptions = function (module) {
var selectedValue = $('option:selected', module).attr('value');
var collectionWithoutCurrent = $('.move-img select').not(module);
$('option').show();
collectionWithoutCurrent.each(function () {
$(this).children('option[value="' + selectedValue + '"]').toggle();
});
};
</script>
<ul>
<li class="move-img">
<select style="width: 150px;" id="modul1" onchange="ValidateOptions($(this))">
<option value="0"></option>
<option value="1">name</option>
<option value="2">name2</option>
</select>
</li>
</ul>
<ul>
<li class="move-img">
<select style="width: 150px;" id="modul2" onchange="ValidateOptions($(this))">
<option value="0"></option>
<option value="1">name</option>
<option value="2">name2</option>
</select>
</li>
</ul>

Categories