Drop-down list selection does not display in div - javascript

I want the displayround div to display what is selected in the selection box. Somehow when I removed some of the array values it stopped working.. Any idea why?
HTML:
<div id="buttonholder">
<button id="previous">< Previous round</button>
<button id="next">Next round ></button>
<button id="current">> Current round <</button>
<div style="font-size: 0;">
<form id="inputform">
<select name="rounds" id="selectbox">
<option value="2013/2014">--- 2013/2014 ---</options>
<option value="2012/2013">--- 2012/2013 ---</options>
<option value="2011/2012">--- 2011/2012 ---</options>
<option value="2010/2011">--- 2010/2011 ---</options>
<option value="2009/2010">--- 2009/2010 ---</options>
<option value="2008/2009">--- 2008/2009 ---</options>
<option value="2007/2008">--- 2007/2008 ---</options>
<option value="2006/2007">--- 2006/2007 ---</options>
</select>
</form>
</div>
<div id="displayround">
</div>
</div>
JQuery:
$(document).ready(function() {
var season = new Array();
season[0]="2013/2014";
season[1]="2012/2013";
season[2]="2011/2012";
season[3]="2010/2011";
season[4]="2009/2010";
season[5]="2008/2009";
season[6]="2007/2008";
season[7]="2006/2007";
season[8]="2005/2006";
$("#buttonholder").find("button").addClass("left")
$("#buttonholder").find("#submit").removeClass("left").addClass("right")
$("#buttonholder").find("#inputform").addClass("right");
$("#displayround").text(season[0]).data('index', 0);
$("#next").click(function () {
var index = +$("#displayround").data('index') + 1;
if (index >= season.length) index = 0;
$("#displayround").text(season[index]).data('index', index);
});
$("#previous").click(function () {
var index = +$("#displayround").data('index') - 1;
if (index <= -1) index = season.length - 1;
$("#displayround").text(season[index]).data('index', index);
})
The problem is somewhere in this function I'm assuming:
$("#selectbox").change(function() {
var index = $(this).val().match(/\d+/) - 1;
$("#displayround").text(season[index]).data('index', index);
});
}); //end of document.ready function

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>

function needs to wait until select tag's value selected

I have a function in my main.js needs to wait until some options selected on select tag. According to that, I will update the element. I tried to do it with addlistenerevent, but I could not succeed it. Any suggestions? Am I doing wrong?
var test = function() {
const langOptions = {
dummy: 0,
one: 5,
two: 8,
three: 2
};
var unit_1 = 1;
var selectSource ="";
var selectTarget = "";
var section = document.getElementById("unit");
var span_1 = '<span>Unit : </span>';
section.insertAdjacentHTML("beforeend", span_1);
var span_2 = '<span id= "span_2">' + unit_1 +'</span>';
section.insertAdjacentHTML("beforeend", span_2);
document.getElementById('source-lang').addEventListener('change', function() {
selectSource = $('source-lang').find('select').val();
for (const key of Object.keys(langOptions)) {
if (key === selectSource || key === selectTarget) { unitPrice *= langOptions[key];}
}
var element = document.getElementById('span_2').innerHTML = unit_1;
});
};
test();
<div id="langs">
<section class="container">
<div class="dropdown">
<select id="source-lang" style="background-color:#5e3080" name="source-lang">
<option value="">Select</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
</select>
</div>
<div class="dropdown">
<select id ="target-lang" style="background-color:#5e3080" name="target-lang">
<option value="">Select</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
</select>
</div>
<div class="dropdown">
<div id="unit"></div>
</div>
</section>
</div>
I think that what you are looking for, is the onchange Event
function selectOne() {
const id = 'selectOne';
console.log(id, document.getElementById(id).value);
}
document.getElementById('selectTwo').addEventListener("change", function() {
console.log(this.id, this.value)
});
<p>Select One</p>
<select id="selectOne" type="text" onchange="selectOne()">
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<!-- Or using addEventListener -->
<p>Select Two</p>
<select id="selectTwo" type="text">
<option value=a>a</option>
<option value=b>b</option>
<option value=c>c</option>
</select>
Use onchange Event
<select id="source-lang" style="background-color:#5e3080" name="source-lang" onchange="test()">
<select id ="target-lang" style="background-color:#5e3080" name="target-lang" onchange="test()">

Remove specific value in Javascript Array dynamically

I want to remove a specific value from an array.
For example:
var categories = ["Lenovo","Large","100"];
I displayed it like this
HTML CODE:
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="brand" >
<option value="">Select a Brand</option>
<option value="Lenovo">Lenovo</option>
<option value="Acer">Acer</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="screen_size" style="margin-top:0px;">
<option value="">Select a Screen Size</option>
<option value="Small">Small</option>
<option value="Large">Large</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="cpu">
<option value="">Select a CPU</option>
<option value="Intel">Intel</option>
<option value="Amd">Amd</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="memory">
<option value="">Select a Memory</option>
<option value="500mb">500mb</option>
<option value="1tb">1tb</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="price">
<option value="">Filter by Price</option>
<option value="10000">10000</option>
<option value="20000">20000</option>
</select>
</div>
How can I achieve this?
I tried it so many times but I failed because I cant get the value. You can check my code:
jQuery("#filter").val()
jQuery(function() {
jQuery("#brand,#screen_size,#cpu,#memory,#price").change(function() {
var brand = jQuery("#brand").val();
var screen_size = jQuery("#screen_size").val();
var cpu = jQuery("#cpu").val();
var memory = jQuery("#memory").val();
var price = jQuery("#price").val();
var categories = [];
if (brand) {
categories.push(brand);
}
if (screen_size) {
categories.push(screen_size);
}
if (cpu) {
categories.push(cpu);
}
if (memory) {
categories.push(memory);
}
if (price) {
categories.push(price);
}
length = categories.length;
categories2 = categories.toString();
var categories3 = "";
for (var i = 0; i < length; i++) {
var cat_id = "cat" + i;
categories3 += "<div class='filter_style'>" + categories[i] + "<a href='" + cat_id + "' id='" + cat_id + "' onclick='removeCat(event)'><span style='margin-left:15px;color:gray;' >x</span></a></div>";
jQuery("#filter").html(categories3);
}   
});
});
function removeCat(evt) {
evt.preventDefault();
var catid = jQuery(this).attr('href');
var cat = jQuery(this).data("id");
//jQuery.grep(); maybe or indexOf first then slice() but I do not get the value
alert(catid);
}
You can simply remove element from array using below method
categories .splice( $.inArray(removeItem, categories), 1 );//removeItem is name of item which you want to remove from array
If you want to remove, for example, "Lenovo" from:
var categories = ["Lenovo","Large","100"];
do:
categories.splice(0)

calculations on multiple selects dropdown

I am trying calculate the amount on change of select dropdown. I need each row calculation front of that row i.e. subtotal and all subtotal will be at bottom at "Total Amount"
I am getting the calculations for first row, but there is issues somewhere, i cannot findout properly. Please help me.
My code is
jQuery(document).ready(function() {
var bookIndex = 1;
jQuery('#orderform')
// Add button click handler
.on('click', '.addButton', function() {
bookIndex++;
var $template = jQuery('#bookTemplate'),
$clone = $template
.clone()
.removeClass('hide')
.addClass('form-group')
.removeAttr('id')
.removeAttr('style')
.attr('id', "row"+bookIndex)
.attr('data-index', bookIndex)
.insertBefore($template);
jQuery("#row"+bookIndex+' .addprice span').addClass('item_price');
jQuery("#row"+bookIndex+' .addprice input').addClass('itemprice');
jQuery("#row"+bookIndex+' > div ').removeClass('addprice');
// Add new fields
// Note that we also pass the validator rules for new field as the third parameter
var totalamount = 0;
var price =0;
jQuery('.dynamic-fields > .form-group').each(function () {
price = jQuery("span.item_price").html();
totalamount += parseFloat( price );
});
jQuery("#totalamount > span").html(totalamount);
jQuery("#totalamount").attr('data-amount', totalamount);
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = jQuery(this).parents('.form-group'),
index = $row.attr('data-book-index');
// Remove fields
// Remove element containing the fields
$row.remove();
var totalamount = 0;
var price =0;
jQuery('.dynamic-fields > .form-group').each(function () {
price = jQuery("span.item_price").html();
totalamount += parseFloat( price );
});
jQuery("#totalamount > span").html(totalamount);
jQuery("#totalamount").attr('data-amount', totalamount);
});
});
jQuery(document).ready(function(){
var totalamount = 0;
var price =0;
jQuery('.dynamic-fields > .form-group').each(function () {
price = jQuery("span.item_price").html();
totalamount += parseFloat( price );
});
jQuery("#totalamount > span").html(totalamount);
jQuery("#totalamount").attr('data-amount', totalamount);
})
jQuery(".dynamic-fields").each(function() {
var tpy = parseInt(jQuery(".service_type option:selected").val());
var clths = parseInt( jQuery(".cloths option:selected").val() );
var quantity = parseInt( jQuery(".quantity option:selected").val() );
var total;
total= tpy + clths * quantity;
jQuery("span.item_price").html(total);
jQuery("input.itemprice").attr('value', total);
});
jQuery(document).on("change", '.dynamic-fields > div.form-group select', function() {
var total = 0;
var id = jQuery(this).parent().parent().attr('id');
var index = jQuery(this).parent().parent().attr('data-index');
id = '#'+id+' '; //alert(id); //alert(index);
//jQuery('.form-group').each(function () {
var tpy = jQuery(id+'.service_type option:selected').val();
var clths = jQuery(id+'.cloths option:selected').val();
var quantity = jQuery(id+'.quantity option:selected').val();
total= ( parseInt(tpy) + parseInt(clths) ) * parseInt(quantity);
jQuery(id+".item_price").html(total);
jQuery(id+".itemprice").attr('value', total);
//});
var totalamount = 0;
var price =0;
jQuery('.accept-checkbox.dynamic-fields > div.form-group').each(function () {
price = jQuery("span.item_price").html();
totalamount += parseFloat( price );
});
jQuery("#totalamount > span").html(totalamount);
jQuery("#totalamount").attr('data-amount', totalamount);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form name="neworder" action="<?php the_permalink(); ?>" method="post" id="orderform">
<div class="accept-checkbox dynamic-fields">
<div class="form-group" id="row1" data-index="1">
<div class="col-sm-3">
<select class="service_type" name="service_type[]">
<option value="20">Iron</option>
<option value="30">Wash</option>
<option value="40">Wash & Iron</option>
<option value="50">Dryclean</option>
</select>
</div>
<div class="col-sm-3">
<select class="cloths" name="cloths[]">
<option value="10">Shirt</option>
<option value="20">Tshirt</option>
<option value="30">Kurta</option>
<option value="40">Jeans</option>
<option value="50">Trouser</option>
<option value="60">Trouser</option>
</select>
</div>
<div class="col-sm-3">
<select class="quantity" name="quantity[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="3">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div class="col-sm-2">
<span class="item_price">30</span>
<input type="hidden" class="itemprice" value="00"/>
</div>
<div class="col-sm-1">
<button class="btn btn-default addButton" type="button"><i class="fa fa-plus">+</i></button>
</div>
</div>
<!-- The template for adding new field -->
<div id="bookTemplate" class=" hide" style="display: none;">
<div class="col-sm-3">
<select class="service_type" name="service_type[]">
<option value="20">Iron</option>
<option value="30">Wash</option>
<option value="40">Wash & Iron</option>
<option value="50">Dryclean</option>
</select>
</div>
<div class="col-sm-3">
<select class="cloths" name="cloths[]">
<option value="10">Shirt</option>
<option value="20">Tshirt</option>
<option value="30">Kurta</option>
<option value="40">Jeans</option>
<option value="50">Trouser</option>
<option value="60">Trouser</option>
</select>
</div>
<div class="col-sm-3">
<select class="quantity" name="quantity[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="3">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div class="col-sm-2 addprice">
<span >30</span>
<input type="hidden" value="00"/>
</div>
<div class="col-xs-1">
<button class="btn btn-default removeButton" type="button"><i class="fa fa-minus"> - </i></button>
</div>
</div>
</div>
<div class="row">
<div class="col-md-5 pull-right">
<span><strong>Total Amount : </strong></span><span id="totalamount"> <span>00.00</span>/- </span>
</div>
</div>
</form>
The added elements do not have an event handler.
To write one event handler for current and future elements, replace this:
jQuery('.dynamic-fields > div.form-group select').on("change", function () {
With:
jQuery(document).on("change", '.dynamic-fields > div.form-group select', function() {
Note that you still have many issues with your code. You should better keep your quantities, prices, etc.. (also) in variables, and not re-read them every time from html attributes.
For instance these lines are now wrong:
jQuery(".item_price").html(total);
jQuery("input.itemprice").attr('value', total);
You intended this:
jQuery(id+".item_price").html(total);
jQuery(id+".itemprice").attr('value', total);
... and there are more issues like that, but if I were you, I would refactor this code to rely less on the html attributes for calculating the total.
change the line
jQuery('.dynamic-fields > div.form-group select').on("change", function() { ...
to
jQuery(document).on("change", '.dynamic-fields > div.form-group select', function() { ...
because the EventListener change is bind once to the elements that are at the time in DOM the code is executed with selector .dynamic-fields > div.form-group select.
Now the EventListener is set to the document und the function is executed when event.target is .dynamic-fields > div.form-group select.

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());
}

Categories