Select elements by index in elements name - javascript

Good morning. I have a form that is divided into numbered sections. Sometimes I need to disable some of these sections by using their section numbers. Right now when the function receives an array of section numbers I run a loop to collect them one-by-one. Is there a better, more efficient way of collecting numbered sections by their section numbers with jQuery?
HTML:
<div id="frameContent">
<div id="section1">
<select>
<option value="1" selected="selected">empty (default)</option>
<option value="2" selected="selected">foo</option>
<option value="3" selected="selected">bar</option>
</select>
</div>
<div id="section2">
<select>
<option value="1" selected="selected">empty (default)</option>
<option value="2" selected="selected">foo</option>
<option value="3" selected="selected">bar</option>
</select>
</div>
<div id="section3"><select>
<option value="1" selected="selected">empty (default)</option>
<option value="2" selected="selected">foo</option>
<option value="3" selected="selected">bar</option>
</select></div>
<div id="section4">
<select>
<option value="1" selected="selected">empty (default)</option>
<option value="2" selected="selected">foo</option>
<option value="3" selected="selected">bar</option>
</select>
</div>
</div>
JS:
var toggleFormSections = function(frameContent, sectionNumbers, enable) {
// init empty selector
var sections = $();
// collect sections
for(var i = 0; i < sectionNumbers.length; i++) {
var section = frameContent.find('div#section' + sectionNumbers[i]);
sections = sections.add(section);
}
// disable/enable sections and elements within
if(sections.length > 0) {
if(enable) {
sections.find('select').prop('disabled', false);
} else {
sections.find('select').prop('disabled', 'disabled');
}
}
}
// usage:
var frameContent = $('#frameContent');
toggleFormSections(frameContent, [2,3], false);
Link to FIDDLE

http://jsfiddle.net/XZ9fT/3/
You can easily use jQuery's each to loop through the index elements, no need to check it's length. I'm not quite sure, why you want the enabled flag. Since you can call it with an empty array to enable everything. This would make it even shorter.
$.each(sectionNumbers, function(i) {
if(enable) {
frameContent.find('div#section' + sectionNumbers[i] + ' select').prop('disabled', false)
} else {
frameContent.find('div#section' + sectionNumbers[i] + ' select').prop('disabled', 'disabled');
}
});

One way will be
var toggleFormSections = function(frameContent, sectionNumbers, enable) {
// init empty selector
var sections = [];
// collect sections
for(var i = 0; i < sectionNumbers.length; i++) {
sections.push('#section' + sectionNumbers[i]);
}
sections = $(sections.join(', '))
sections.find('select').prop('disabled', !enable);
}
Demo: Fiddle

Related

Update Array with dynamically generated values

I'm very new to JavaScript, so I'm having a hard time with this relatively simple problem:
I wrote a function that dynamically adds or removes dropdown fields to the DOM if the user clicks the add or remove button. So far so good, everything is working fine until here.
Now I want to collect the data in an Array to send it to the api.
With the following code I can collect it, but I have a hard time to figure out how I can remove specific values from the array.
<div class="container mt-2" id="stores">
<div class="row">
<div class="col">
<h2>Marktet</h2>
<div class="col-form-label storesHint">Select at least one market</div>
</div>
</div>
<div id="form">
<div>
<div id="addAnotherMarket">
<div class="marketRow">
<select class="form-control" id="market" name="market">
<option value="1"> market1</option>
<option value="2"> market2</option>
<option value="3"> market3</option>
<option value="4"> market4</option>
<option value="5"> market5</option>
</select>
<input class="deleteButton" type="button" id="remove" value="" style="display: none; font-family: FontAwesome, 'Helvetica Neue', Helvetica, Arial, sans-serif;">
</div>
</div>
</div>
</div>
<div>
<div class="addBtnContainer">
<div class="centerBtn">
<a class=" button btn_gray buttonWithIcon" id="add">
<i class=" fa fa-plus icn" id="btnIcon" style="font-size: 16px;" aria-hidden="true"></i>
<span class="btnText spn" style="top:0px !important">Add another market</span>
</a>
</div>
</div>
</div>
</div>
$(document).ready(function () {
let index = 0;
let store = {};
let stores = [];
var oldValue = [];
window.Stores = stores;
//set initial value for the first dropdown element
store = { "store_id": parseInt($('#market').val(), 10) };
stores.push(store);
oldValue[index] = store;
//update value if user changes first element
$('#market').on('change', function () {
store = { "store_id": parseInt($(this).val(), 10) };
var eleIndex = stores.indexOf(oldValue[index]);
if (eleIndex !== -1) {
stores.splice(eleIndex, 1, store);
oldValue[index] = store;
}
});
//add a new dropwdown element
$("#add").click(function () {
index++;
$(this).parent().parent().before($("#form").clone().attr("id", "form" + index));
$("#form" + index + " :input").each(function () {
$(this).attr("name", $(this).attr("name") + index);
$(this).attr("id", $(this).attr("id") + index);
});
//set initial value of the new dropdown element
store = { "store_id": parseInt($('#market' + index).val(), 10) };
stores.push(store);
oldValue[index] = store;
//set new value if user changes value
$('#market' + index).on('change', function () {
store = { "store_id": parseInt($(this).val(), 10) };
var eleIndex = stores.indexOf(oldValue[index]);
if (eleIndex !== -1) {
stores.splice(eleIndex, 1, store);
oldValue[index] = store;
}
});
//add remove button
$("#remove" + index).css("display", "inline-flex");
$(".marketRow").css({
'display': 'flex',
'align-items': 'center',
'margin-top': '5px'
});
//if user clicks remove button delete value from array
$("#remove" + index).click(function () {
var eleIndex = stores.indexOf({ "store_id": parseInt($('#market' + index).val(), 10) });
if (index !== -1) {
stores.splice(eleIndex, 1);
oldValue.splice(eleIndex);
}
$(this).closest("div").remove();
});
});
});
The following code also outputs -1 always, so I think indexOf makes no sense.
var eleIndex = stores.indexOf({"store_id": parseInt($('#market' + index).val(), 10)});
EDIT: I updated the post with the HTML part as requested. In short: When clicking on button(#add) div(#form) will be cloned, remove button will be added, and id's will be updated with index.
Values of all these selects will be stored and updated in the stores array. I just can't delete them.
I have also provided a working jsfiddel https://jsfiddle.net/proach1995/h1gtmyen/
With plain js you can add class to the dropdown you wish to collect from. in the code below it will build the array only if value was selected.
if you use jQuery you can replace document.querySelectorAll('.store'); with $('.store');
function saveArray() {
const selected = document.querySelectorAll('.store');
const stores = [];
selected.forEach(prop => {
if (!!prop.value) {
stores.push({store_id: parseInt(prop.value, 10)})
}
});
console.log(stores);
}
<select class="store">
<option disabled selected value>select value</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="store">
<option disabled selected value>select value</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<select class="store">
<option disabled selected value>select value</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<button onclick="saveArray()">save array</button>

How to create hyperlink with pre-selected option in drop down list on the same page in pop up?

I am trying to get to work pre selecting an option in a pop up window. I've done my research on the internet and this is what I got so far but it doesn't work. I now always have option number one pre selected
Hyperlink triggering showing the pop up, where option two should be pre selected.
Order!
Modal Window, which shows up and the option two should be pre selected.
<div id="order-form-modal" class="modal-window">
<select class="prettyform" name="select" id="select">
<option id="one" value="1" data-price="950">Nízke stojánky</option>
<option id="two" value="2" data-price="1790">Vysoké stojánky</option>
<option id="three" value="3" data-price="990">Set přenosné kruhy</option>
<option id="four" value="4" data-price="790">Přenosné kruhy</option>
<option id="five" value="5" data-price="490">Popruhy na kruhy</option>
</select>
</div>
JavaScript which should parse the parameter given in hyperlink at the beginning.
<script>
$(document).ready(function() {
var select = GetUrlParameter("select");
$("#" + select).attr("selected", "");
});
function GetUrlParameter(name) {
var value;
$.each(window.location.search.slice(1).split("&"), function (i, kvp) {
var values = kvp.split("=");
if (name === values[0]) {
value = values[1] ? values[1] : values[0];
return false;
}
});
return value;
}
</script>
You need to set the selected property on the option to true:
var select = GetUrlParameter("select");
$("#" + select).prop("selected", true);
Example fiddle

Default value in dropdown menu (JavaScript)

I wish to set the default value in a dropdown menu to the middle one (not the first).
I use dropdowns on my site for visitors to choose one of three / four / five sizes of a product.
The JavaScript is:
$(document).ready(function () {
$('.group').hide();
$('#option1').show();
$('#selectMe').change(function () {
$('.group').hide();
$('#'+$(this).val()).show();
})
});
The other code is:
<select id="selectMe">
<option value="option1">S</option>
<option value="option2">M</option>
<option value="option3">L</option>
</select>
User chooses a value, and then the BUY button changes accordingly. Thus ...
<div>
<div id="option1" class="group">Button for size S</div>
<div id="option2" class="group">Button for size M</div>
<div id="option3" class="group">Button for size L</div>
</div>
This works great, but in this instance, I want M to be the default, and not S (there are three sizes here, but sometimes there are more).
Why don't you make a selected property?
<option value="option2" selected>M</option>
Just use following snippets:
With jQuery
$(document).ready(function () {
var $select = $('#selectMe');
$select.val("option2");//initial value
$("[id=" + $select.val() + "]").show()
.siblings().hide();
$select.change(function () {
$("[id=" + $select.val() + "]").show()
.siblings().hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select id="selectMe">
<option value="option1">S</option>
<option value="option2">M</option>
<option value="option3">L</option>
</select>
<div>
<div id="option1" class="group">Button for size S</div>
<div id="option2" class="group">Button for size M</div>
<div id="option3" class="group">Button for size L</div>
</div>
Or, You can do it through pure JavaScript
var selectBox = document.getElementById("selectMe")
selectBox.selectedIndex = parseInt(selectBox.length / 2);
selectBox.onchange = function () {
changeButton(this.value);
}
changeButton(selectBox.value);
function changeButton(val) {
console.log(val)
var i = -1, elements = document.querySelectorAll('[class=group]');
while (elements[++i]) {
console.log(elements[i]);
elements[i].style.display = (elements[i].id == val) ? "block" : "none";
}
}
<select id="selectMe">
<option value="option1">S</option>
<option value="option2">M</option>
<option value="option3">L</option>
</select>
<div>
<div id="option1" class="group">Button for size S</div>
<div id="option2" class="group">Button for size M</div>
<div id="option3" class="group">Button for size L</div>
</div>
You got 3 options
1.Using HTML selected property for the option you want.
<select id="selectMe">
<option value="option1">S</option>
<option value="option2" selected>M</option>
<option value="option3">L</option>
</select>
2.Using jQuery
$('#selectMe').val('option2')
3.Using pure JS
document.getElementById('selectMe').value = 'option2';
Try this:
var options = $('#selectMe option');
var total = options.length + ((options.length % 2 == 0) ? 0 : -1);
var value = $(options[total / 2]).val();
$('#selectMe').val(value);
Try with one button:
HTML:
<select id="selectMe">
<option value="option1">S</option>
<option value="option2">M</option>
<option value="option3">L</option>
</select>
...
<div>
<div id="button-size" class="group">Button for size S</div>
</div>
jQuery:
var options = $('#selectMe option');
var total = options.length + ((options.length % 2 == 0) ? 0 : -1);
var value = $(options[total / 2]).val();
$('#selectMe').val(value);
changeButtonLabel(value);
$('#selectMe').on('change', function (evt)
{
var value = $(this).val();
changeButtonLabel(value);
});
function changeButtonLabel(value)
{
$('#button-size').html('Button for size ' + $('#selectMe').find('option[value=' + value + ']').html());
}

Load array from dynamically created input fields

I have a page that creates a number of inputs based on the user's selection of how many to create:
select id="noOfDirectors" name="amount" onchange="addInput();">
<option value="">How Many Directors</option>
<option value="1" >1</option>
<option value="2" >2</option>
<option value="3" >3</option>
<option value="4" >4</option>
<option value="5" >5</option>
<option value="6" >6</option>
<option value="7" >7</option>
<option value="8" >8</option>
<option value="9" >9</option>
<option value="10" >10</option>
</select>
<div id="inputs"></div><br/>
<button id="nod" onclick="return false">Submit</button>
The .js file creates the forms:
function addInput(){
noOfDirectors = $('#noOfDirectors').val();
var inputs = $('#inputs').empty();
inputs.innerHTML = "";
for(i = 0; i < noOfDirectors; i++) {
inputs.append('Director '+ (i+1) +' Name: <input type="text" name="directorName[' + i + ']" /><br/>Director '+ (i+1) +' Customer Number: <input type="text" name="directorECN['+i+']" /><br/><br/>');
}
$("#nod").show();
directors = $('[name^=directorECN]').map(function(i) {
//return this.name;
return this.value; // for real values of input
}).get();
}
$(document).ready(function() {
$('#nod').click(function() {
console.log(directors);
});
});
Now, I want to take each of those directorECN['+i+'] input names and add them to a globally declared array:
var directors = new Array ();
I am having a hard time figuring out a syntax that works without hard coding 10 (0-9) of each of the possible input names. Is there an easier way to do this?
Here is my UPDATED JSFiddle
Updated my JS above. Console is printing [""]
You can use .map() to get the array from name attribute of elements returned by Attribute Starts With Selector [name^=”value”].
var directors = $('[name^=directorECN]').map(function(i) {
//return this.name;
return this.value; // for real values of input
}).get();
Use .map() function over the attribute starts with selector [attribute^="value"]
var directors = $('[name^="directorECN"]').map(function () {
return this.name //to get value use this.value
}).get();
Updated Fiddle

Change contents in dropdown using javascript

Think I'm making this harder than it need to be. here is my jsfiddle http://jsfiddle.net/justmelat/pArU7/2/
straight html:
<form>
.
<input type="radio" name="sex" value="House">House
<input type="radio" name="sex" value="Cars">Cars
<hr>
<select name="cars">
<option value="0">--Select--</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="wood">Wood</option>
<option value="audi">Audi</option>
<option value="brick">Brick</option>
</select>
</form>
when user selects house, i only want the select, wood and brick options to appear in the dropdown
of course if cars is selected then wood and brick should disappear.
How can I easily do this in javascript?
Demo: http://jsfiddle.net/33tJR/
Just a quick mockup I made, nothing too fancy using jQuery or anything
function createOption(value) {
el = document.createElement('option');
el.value = value;
el.innerHTML = value;
el.id = value;
document.getElementById('select').appendChild(el);
}
document.getElementById('house').addEventListener('click', function() {
document.getElementById('select').innerHTML = '';
createOption('Volvo');
createOption('Saab');
createOption('Fiat');
});
document.getElementById('cars').addEventListener('click', function() {
document.getElementById('select').innerHTML = '';
createOption('Wood');
createOption('Brick')
});
Use the onchange event of radio button and if the value matches to male , call a javascript which will create the option list and clear the exisiting list and append the new one. All these used jquery
$(document).ready(function(){
$("input[name='sex']").change(function() {
if($(this).value === "male") { loadDLLWithOption1(); }
else { loadDLLWithOption2(); }
}
});
function loadDLLWithOption1()
{
var optionList = '<option>option1</option><option>option2</option>';
$("#cars").html(optionList);
}

Categories