JS doesn't detected when I change Option, Variable keeps undefined - javascript

I'm trying to generate an automatic email address, based on user change.
The point is to print the domain name, the rest is working fine.
here is my issue, I'm getting the element ID, if the element ID the Var x takes the values of an other var depending on the selection however, X keeps undefined.
I think that somehow it doesn't detect when I select an other option.
Any kind of help will be much appreciated.
<select name="select" id="selecto">
<option value="">--Please choose an option--</option>
<option value="value1" id="1">SEE</option>
<option value="value2" id = "2">Guillebert</option>
<option value="value3" id = "3">Saelen</option>
<option value="value4" id ="4">SEE Produktion</option>
<option value="value5" id ="5">TS-Industrie</option>
<option value="value6" id="6">Schliesing</option>
</select>
<script type="text/javascript">
var a = "#groupesee.com";
var b = "#guillebert.fr";
var c = "#saelen.fr";
var d = "#see-produktion.net;"
var e = "#ts-industrie.de";
var g = "#schliesing.net";
var x;
if(document.getElementById('selecto').value == "value1") {
x = a;
alert("Success");
}
</script>
For some reason, and I do not understand why, the var x, is keeping null even if I select the value1 in my form.
<script>
$("#field1, #field2").keyup(function(){
update();
});
function update() {
$("#result").val($('#field1').val().substr(0,1).toLowerCase() + $('#field2').val().toLowerCase()+x);
}
</script>
Result

Your code just runs as it loads. It only checks the value of the select element once (as the page loads and the script element is executed).
If you want it to run every time the select element is changed, then you need to say so.
Put your code in a function
Find the select element in the DOM
Listen for the value to change and call the function

Here is the fix, using the in the Update function. :) Tyvm #Quentin
function update() {
var a = "#groupesee.com";
var b = "#guillebert.fr";
var c = "#saelen.fr";
var d = "#see-produktion.net;"
var e = "#ts-industrie.de";
var g = "#schliesing.net";
var x;
var elt = document.getElementById(selecto);
if(document.getElementById('selecto').value == "value1") {
x = a;
} if(document.getElementById('selecto').value == "value2") {
x = b;
}
if(document.getElementById('selecto').value == "value3") {
x = c;
}
if(document.getElementById('selecto').value == "value4") {
x = c;
}
if(document.getElementById('selecto').value == "value5") {
x = c;
}
if(document.getElementById('selecto').value == "value6") {
x = c;
}
$("#result").val($('#field1').val().substr(0,1).toLowerCase() + $('#field2').val().toLowerCase()+x);
}

Related

Why my if condition isn't working with select box in javascript?

In my code, I am trying to make a code in which I want to get value of select box and add value accordingly but my code is getting a bunch of errors. Can anyone please help me. In code i just want to add 1 to selectbox value. E.g: If i pressed on S and add then 1 should be added to S Code:
function myFunction() {
var x = document.getElementById("issue").value;
var is1 = 0;
var is2 = 0;
var is3 = 0;
if (x == document.getElementById("issue").value) {
is1 = 1;
} else if (x == document.getElementById("issue").value) {
is2 = 1;
} else if (x == document.getElementById("issue").value) {
is3 = 1;
}
}
Enter issue code:
<select name="issue" id="issue">
<option value="i1">S</option>
<option value="i2">W</option>
<option value="i3">T</option>
</select>
<button onclick="myFunction()">Add</button>
You can simply create three variables and update their count based on the selected option.
let is1 = 0, is2 = 0, is3 = 0
function myFunction() {
var x = document.getElementById("issue").value;
if (x === "i1") is1++
else if (x === "i2") is2++
else if (x === "i3") is3++
document.getElementById("results").innerText=`Option S: ${is1}\nOption W: ${is2}\nOption T: ${is3}`
}
Enter issue code:
<select name="issue" id="issue">
<option value="i1">S</option>
<option value="i2">W</option>
<option value="i3">T</option>
</select>
<button onclick="myFunction()">Add</button>
<p id="results"></p>

Issue with event listener and value not updating

I am having an issue with an event listener on a select and a value not updating but cannot figure out what the issue.
Code is below. Basically need the price field to update based on the function above it. Unfortunately i cannot have them all in the same function and need to have them separate. The first console.log does show the value for y but the second does not show the value for price.
var factors = function factor(j) {
var mySelect = document.getElementById("mySelect").value;
if (mySelect == "car") {
lease = "166";
} else if (mySelect == "truck") {
lease = "200";
}
console.log("this is my lease value - " + lease);
return lease * j;
};
var monthlyprice = function monthlyprice() {
var price = factors(1);
console.log("this is my price -" + price);
};
var type = document.getElementById("mySelect");
type.addEventListener("click", factors);
<form action="">
<label for="mySelect">Shipment Type</label>
<select id="mySelect">
<option value="car">Car</option>
<option value="truck">Truck</option>
</select>
</form>
since monthlyprice calls factor() you want to place the listener on monthlyprice
var type = document.getElementById("mySelect");
type.addEventListener("change", monthlyprice);
function monthlyprice() {
var price = factor(1)
console.log("this is my price =" + price);
};
function factor(j) {
var y;
var z = document.getElementById("mySelect").value;
if (z == "car") {
y = "166";
} else if (z == "truck") {
y = "200";
}
console.log("this is my y value - " + y);
return y * j;
};
<form action="">
<label id="label">Shipment Type</label>
<select id="mySelect">
<option value="car">Car</option>
<option value="truck">Truck</option>
</select>
</form>

Select prepended option by default

Okay I'm about to pull my hair out.
I'm hoping someone can help me.
I'm trying to prepend a "Select an Option" value to a dropdown menu and then make that the default selected option when the page loads.
For a brief background: I have been trying to combine Shopify's "Linked Options" and "Pick an Option" features. Sadly, when you try to implement both, the Linked Options feature overrides Pick an Option. (Pick an Option places a default "Select a ____" to the dropdown menu).
So I have taken a part of the Pick an Option and tried placing it in Linked Options.
Here is the code that I placed in that:
selector.prepend('<option value="">Select ' + {{ product.options[forloop.index0] | json }} + '</option>').val('');
And here is the entire code:
<script>
// (c) Copyright 2016 Caroline Schnapp. All Rights Reserved. Contact: mllegeorgesand#gmail.com
// See https://docs.shopify.com/themes/customization/navigation/link-product- options-in-menus
var Shopify = Shopify || {};
Shopify.optionsMap = {};
Shopify.updateOptionsInSelector = function(selectorIndex) {
switch (selectorIndex) {
case 0:
var key = 'root';
var selector = jQuery('.single-option-selector:eq(0)');
break;
case 1:
var key = jQuery('.single-option-selector:eq(0)').val();
var selector = jQuery('.single-option-selector:eq(1)');
break;
case 2:
var key = jQuery('.single-option-selector:eq(0)').val();
key += ' / ' + jQuery('.single-option-selector:eq(1)').val();
var selector = jQuery('.single-option-selector:eq(2)');
}
var initialValue = selector.val();
selector.empty();
var availableOptions = Shopify.optionsMap[key];
selector.prepend('<option value="">Select ' + {{ product.options[forloop.index0] | json }} + '</option>');
selector[0].selectedIndex = 0;
for (var i=0; i<availableOptions.length; i++) {
var option = availableOptions[i];
var newOption = jQuery('<option></option>').val(option).html(option).val('');
selector.append(newOption);
}
jQuery('.swatch[data-option-index="' + selectorIndex + '"] .swatch-element').each(function() {
if (jQuery.inArray($(this).attr('data-value'), availableOptions) !== -1) {
$(this).removeClass('soldout').show().find(':radio').removeAttr('disabled','disabled').removeAttr('checked');
}
else {
$(this).addClass('soldout').hide().find(':radio').removeAttr('checked').attr('disabled','disabled');
}
});
if (jQuery.inArray(initialValue, availableOptions) !== -1) {
selector.val(initialValue);
}
selector.trigger('change');
};
Shopify.linkOptionSelectors = function(product) {
// Building our mapping object.
for (var i=0; i<product.variants.length; i++) {
var variant = product.variants[i];
if (variant.available) {
// Gathering values for the 1st drop-down.
Shopify.optionsMap['root'] = Shopify.optionsMap['root'] || [];
Shopify.optionsMap['root'].push(variant.option1);
Shopify.optionsMap['root'] = Shopify.uniq(Shopify.optionsMap['root']);
// Gathering values for the 2nd drop-down.
if (product.options.length > 1) {
var key = variant.option1;
Shopify.optionsMap[key] = Shopify.optionsMap[key] || [];
Shopify.optionsMap[key].push(variant.option2);
Shopify.optionsMap[key] = Shopify.uniq(Shopify.optionsMap[key]);
}
// Gathering values for the 3rd drop-down.
if (product.options.length === 3) {
var key = variant.option1 + ' / ' + variant.option2;
Shopify.optionsMap[key] = Shopify.optionsMap[key] || [];
Shopify.optionsMap[key].push(variant.option3);
Shopify.optionsMap[key] = Shopify.uniq(Shopify.optionsMap[key]);
}
}
}
// Update options right away.
Shopify.updateOptionsInSelector(0);
if (product.options.length > 1) Shopify.updateOptionsInSelector(1);
if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
// When there is an update in the first dropdown.
jQuery(".single-option-selector:eq(0)").change(function() {
Shopify.updateOptionsInSelector(1);
if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
return true;
});
// When there is an update in the second dropdown.
jQuery(".single-option-selector:eq(1)").change(function() {
if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
return true;
});
};
{% if product.available and product.options.size > 1 %}
var $addToCartForm = $('form[action="/cart/add"]');
if (window.MutationObserver && $addToCartForm.length) {
if (typeof observer === 'object' && typeof observer.disconnect === 'function') {
observer.disconnect();
}
var config = { childList: true, subtree: true };
var observer = new MutationObserver(function() {
Shopify.linkOptionSelectors({{ product | json }});
observer.disconnect();
});
observer.observe($addToCartForm[0], config);
}
{% endif %}
That looks like it'll take way too much time to grok. Snippet 1 demonstrates how to prepend an option to a select. Snippet 2 demonstrates how to use insertAdjacentHTML(). The attribute: selected which value can be: "selected" or true/false, purpose is to designate the default option. Details are commented in the code.
SNIPPET 1
// Reference the select
var sel = document.getElementById('sel');
// Create an option
var opt = document.createElement('option');
// Add a value
opt.value = '0';
// Add content
opt.textContent = '0';
// Make it default
opt.setAttribute('selected', true);
// Reference the first child of the select
var first = sel.firstChild;
// Insert box before the first
sel.insertBefore(opt, first);
<select id='sel' name='sel'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
</select>
SNIPPET 2
var sel = document.getElementById('sel');
sel.insertAdjacentHTML('afterbegin', '<option value="" selected=true>Select</option>');
// Reference the first child of select
var first = sel.firstChild;
// This commented out because I don't have the data to use it.
// first.textContent = "Select "+{{product.options[forloop.index0] || json}}+";
<script src='https://cdn.jsdelivr.net/handlebarsjs/4.0.5/handlebars.min.js'></script>
<select id='sel' name='sel'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
</select>
The first parameter of insertAdjacentHTML() is the location of insertion:
<section id='s1'>Content xxxxxxxxxxxxxxxxxxxxx</section>
▲-----------------▲----------------------------▲---------▲
beforebegin___afterbegin________________beforeend_afterend
The second parameter is the string that will be parsed into HTML. Basically inserAdjacentHTML() is innerHTML on steroids. Read about here.

How to create a select that depends on the value of another select?

I need to create a menu of regions hat display two lists: a <select> for the region and another <select> for the available municipalities of that region. For this, I have a <form> and I update the municipalities through JavaScript. I have problems assigning the municipalities as <option>s of the second <select>. The option matrix of the menu doesn't accept the assignment of the values.
Here's the code.
HTML.
<html>
<head>
<title>
Página menú principal.
</title>
<?!= incluirArchivo('ArchivoJS'); ?>
</head>
<body onLoad = "preparar();">
<form id="formularioConductor" name="formularioConductor" method="post" enctype="multipart/form-data" autocomplete = "on">
<select name="menuDepartamento" id="menuDepartamento" tabindex="2" accesskey="e" onChange="municipiosDepartamento();">
<option value="x" selected="selected">ELIJA UN DEPARTAMENTO</option>
<option value="0">Antioquia</option>
<option value="1">Atlántico</option>
</select>
<select name="menuMunicipios" id="menuMunicipios" tabindex="3" disabled>
<option value=0>TODOS LOS MUNICIPIOS</option>
</select>
</form>
</body>
</html>
Javascript code:
<script lenguage="javascript">
function preparar() {
document.forms[0].elements.numeroLicencia.focus();
document.forms[0].elements.nombreConductor.disabled = true;
document.forms[0].elements.botonEnviar.disabled = true;
document.forms[0].elements.botonActualizar.disabled = true;
}
function municipiosDepartamento() {
var arregloMunicipiosDepartamento = new Array();
var posicionMunicipio = document.forms[0].elements.menuDepartamento.value;
arregloMunicipiosDepartamento = municipiosColombia(posicionMunicipio);
if(document.forms[0].elements.menuMunicipios.options.length > 1){
var totalMunicipios = document.forms[0].elements.menuMunicipios.length;
for (var i = 1; i < totalMunicipios; i ++){
document.forms[0].elements.menuMunicipios.options[1] = null;
}
}
if(document.forms[0].elements.menuDepartamento.value === "x"){
document.forms[0].elements.menuMunicipios.selectedItem = 0;
document.forms[0].elements.menuMunicipios.disabled = true;
}
else
{
document.forms[0].elements.menuMunicipios.options.length = arregloMunicipiosDepartamento.length;
for (var i = 0; i < arregloMunicipiosDepartamento.length; i ++) {
var opcionTemporal = new Option(arregloMunicipiosDepartamento[i], (i+1));
***document.forms[0].elements.menuMunicipios.options[i+1].text = opcionTemporal.text;
document.forms[0].elements.menuMunicipios.options[i+1].value = opcionTemporal.value;***
}
document.forms[0].elements.menuMunicipios.disabled = false;
}
}
function municipiosColombia(posicion) {
var antioquia, atlantico, arregloTodos, arregloMunicipiosDepartamento = new Array();
antioquia=["Medellín","Abejorral","Abriaqui","Alejandria"];
atlantico = ["Barranquilla","Baranoa","Campo De La Cruz","Candelaria"];
arregloTodos = [antioquia, atlantico];
arregloMunicipiosDepartamento=arregloTodos[posicion];
return arregloMunicipiosDepartamento;
}
</script>
I have highlighted the work that doesn't work.
The way I would do what you describe is to clear out the options each time and recreate the required ones, then add them into the particular select, like so:
var regions = {};
regions['A'] = ['mu', 'ni', 'ci', 'pal', 'it', 'y'];
regions['B'] = ['I', 'like', 'bananas'];
var selRegion = document.getElementById('region');
selRegion.onchange = setMunicipalities;
var selMun = document.getElementById('municipality');
function setMunicipalities(e)
{
while(selMun.length > 0)
{
selMun.remove(0);
}
if(selRegion.selectedOptions[0].value === 'ALL')
{
for(var r in regions)
{
if(regions.hasOwnProperty(r))
{
addMunicipalities(regions[r]);
}
}
}
else
{
var reg = selRegion.selectedOptions[0].value;
addMunicipalities(regions[reg]);
}
}
function addMunicipalities(region)
{
var allMun = document.createElement('option');
allMun.setAttribute('value', 'ALL');
var allMunText = document.createTextNode('ALL');
allMun.appendChild(allMunText);
selMun.add(allMun);
for (var mi = 0; mi < region.length; mi++)
{
var m = region[mi];
var mun = document.createElement('option');
mun.setAttribute('value', m);
var munText = document.createTextNode(m);
mun.appendChild(munText);
selMun.add(mun);
}
}
setMunicipalities(null);
<label for="region">Region</label>
<select id="region">
<option selected="selected" value="ALL">ALL</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<label for="municipality">Municipality</label>
<select id="municipality">
</select>
I haven't read your entire code because I had a hard time reading code with contents not in English but anyway, I get what you're trying to do here. Suppose that your first select list contains "Region A" and "Region B" as options; "Municipality A1", "Municipality A2", "Municipality B1","Municipality B2" are the possible options for the second select list. Here's a function that will change the options of the second select list depending on what is selected on the first select list:
function optionChanger(v_selected){
var whatisselected= v_selected.options[v_selected.selectedIndex].value;
var municipalities= {};
municipalities['A'] = ['Municipality A1','Municipality A2'];
municipalities['B'] = ['Municipality B1','Municipality B2'];
v_selected.options.length=0; //remove the contents of the second select list
v_selected.options[0] = new Option(municipalities[whatisselected][0],municipalities[whatisselected][0],false,true);// set the first option of the second list as the default selected value
for(x=1;x<municipalities[whatisselected].length;x++){ //add the remaining options to the second list
v_selected.options[x] = new Option(municipalities[whatisselected][x],municipalities[whatisselected][x],false,false);
}
}
Then add this inside the tag of your FIRST select list:
onchange='optionChanger(this)'
PS: Please notice that the return value of the first select list must be 'A', 'B'

Javascript variable value not refreshing in alert box

Please help me to fix this. The issue is when i select Bangalore and choose any name from 2nd level select and click on button than result is fine, now without refreshing page i choose Hyderabad and a value from 2nd level select and click on button it is still showing value from Bangalore's 2nd level value in alert.
Code:
<div class="Banglore">
<select class="second-level-select" id="start_1">
<option value="">-Select Your Area-</option>
<option value="Mettuguda">Mettuguda</option>
<option value="Lingampally">Lingampally</option>
</select>
</div>
<div class="Hydrabad" >
<select class="second-level-select" id="start_2">
<option value="">-Select Your Area-</option>
<option value="A F Hospital">A F Hospital</option>
<option value="Abbur">Abbur</option>
</select>
Script:
function startAjax() {
var a1 = $("#start_1").val();
var a2 = $("#start_2").val();
if(a1 != ''){
var b = a1;
}else{
var b = a2;
}
alert(b);
}
$(document).ready(function() {
$('#Rank').bind('change', function() {
var elements = $('div.container').children().hide(); // hide all the elements
var value = $(this).val();
if (value.length) { // if somethings' selected
elements.filter('.' + value).show(); // show the ones we want
}
}).trigger('change');
});
for more detail: http://jsfiddle.net/72pbbsfy/2/
Thanks for help!
window.startAjax = function() {
var rank = $("#Rank").val();
var a1 = $("#start_1").val();
var a2 = $("#start_2").val();
var b;
if (rank === 'Banglore') {
b = a1;
} else if (rank === 'Hydrabad') {
b = a2;
} else {
b = 'not selected'
}
alert(b);
}

Categories