I'm building an online shop. From the dropdown the end user picks one option in the select option, and then the price of that option is added to the main price.
<div id='custom-price'>1000</div>
<select id="capsize-price" onchange="changePri()" name="capsize-price">
<option value='100'>100</option>
<option value='700'>700</option>
</select>
function changePri() {
var customPrice = parseFloat(document.querySelector("#custom-price").textContent);
var capsizePrice = document.querySelector("#capsize-price").value;
var price = customPrice + capsizePrice;
document.querySelector("#custom-price").textContent = price;
}
I've got that alright, but then I noticed that the price keeps adding.
For example, if the end user selects only option 1(100) first, and then later selects only option 2 (700) it adds the price of both.
I know this is what it is supposed to do based on my code but I am struggling to come up with logic on how to just add option 1 when the user selects that and then add just option 2 when the user selects option 2 instead of what it is doing right now.
Any help is appreciated.
Your logic here is making it impossible to know what the original price was once the user has selected a capsize-price. You need to store the original value of custom-price somewhere and use it when generating the final price. For example:
<div id='original-price'>1000</div>
<div id='custom-price'></div>
<select id="capsize-price" onchange="changePri()" name="capsize-price">
<option value='100'>100</option>
<option value='700'>700</option>
</select>
function changePri() {
var originalPrice = parseFloat(document.querySelector("#original-price").textContent);
var capsizePrice = document.querySelector("#capsize-price").value;
var customPrice = originalPrice + capsizePrice;
document.querySelector("#custom-price").textContent = customPrice;
}
Not sure this is what you are looking for ?
function changePri() {
var capsizePrice = parseInt(document.querySelector("#capsize-price").value);
var price = basePrice + capsizePrice;
document.querySelector("#custom-price").textContent = price;
}
const basePrice = 1000;
document.querySelector("#custom-price").textContent = basePrice;
<div id='custom-price'></div>
<select id="capsize-price" onchange="changePri()" name="capsize-price">
<option value='100'>100</option>
<option value='700'>700</option>
</select>
Basically puts your "base price" into a JS constant and the adds the selections to that. You should probably use a handler rather than calling the function inline also.
Related
I have a select drop-down with country and code. In drop-down option, for user experience and understanding i am displaying name of the country along with country code.
As a normal functionality when a user selects any value from the drop-down that value gets displayed inside the input like this
however i want that only the country code should get displayed like this
Part of my code
<select name="countrycode" class="form-control pf-country" id="countrycode">
<option data-countryCode="IN" value="91">Code</option>
<option data-countryCode="IN" value="91">India (+91)</option>
<option data-countryCode="US" value="1">USA (+1)</option>
<optgroup label="Other countries">
<option data-countryCode="DZ" value="213">Algeria (+213)</option>
<option data-countryCode="AD" value="376">Andorra (+376)</option>
</optgroup>
</select>
The entire code is available here
Can anyone please suggest how to do it.
As per my understanding, You can try this one. As this example providing exact output as you mentioned in your questions.
https://silviomoreto.github.io/bootstrap-select/examples/#selected-text
Basically we're trying to change innerText of selected-option. It can be achieved easily by adding onchange event listener to the select tag.
But there's a little problem, on changing innerText we lose previous value of innerText, solution by #KKK solves problem but leaves this little thing.
Following code handles problem in complete ways. We're adding data-innerText atribute with previous value of innerText and also id="previous" to identify it. Please check this demo.
function simpleTweak(select){
var previouslySelectedTag = document.getElementById('previous');
if(previouslySelectedTag!=undefined){
previouslySelectedTag.innerText = previouslySelectedTag.getAttribute('data-innerText');
previouslySelectedTag.setAttribute('id','');
}
var innerText = select.options[select.selectedIndex].innerText;
select.options[select.selectedIndex].setAttribute('data-innerText',innerText);
select.options[select.selectedIndex].setAttribute('id','previous');
var value="(+"+select.options[select.selectedIndex].value+")";
select.options[select.selectedIndex].innerText = value;
}
As I understood, you need to change the display text after selecting the option, is it? If so, you can do it like this.
You can set the selected index's text in onchange event. But it will reset the text in the option when you click the dropdown again. You may need to change it back if you prefer.
function displayCountryCode() {
var countrycode = document.getElementById("countrycode");
countrycode.options[countrycode.selectedIndex].text = '+' + countrycode.value;
}
<select name="countrycode" class="form-control pf-country" id="countrycode" onchange="displayCountryCode()">
<option data-countryCode="IN" value="91">Code</option>
<option data-countryCode="IN" value="91">India (+91)</option>
<option data-countryCode="US" value="1">USA (+1)</option>
<optgroup label="Other countries">
<option data-countryCode="DZ" value="213">Algeria (+213)</option>
<option data-countryCode="AD" value="376">Andorra (+376)</option>
</optgroup>
</select>
The following JavaScript code will change the text of the selected option when you select it and change it back when you select a different one.
It does this by saving the values of the country name and country number as HTML5 data attributes (option.dataset.countryName & option.dataset.countryNumber)
Doing it this way, you don't have to change the format of the HTML from what you provided in your post.
I used vanilla JavaScript, so it'll work with or without jQuery.
window.addEventListener('load', () => {
let select = document.getElementsByName('countrycode')[0]
let options = document.getElementsByTagName('option')
for (let i = 1; i < options.length; i++) {
let option = options[i]
let matches = option.innerText.match(/(.*?) (\(\+\d+\))/)
option.dataset.countryName = matches[1]
option.dataset.countryNumber = matches[2]
// Set the value in the collection again now that the object has been changed
options[i] = option
}
select.addEventListener('change', () => {
for (let i = 1; i < options.length; i++) {
let option = options[i];
option.innerText = option.dataset.countryName + ' '
option.innerText += option.dataset.countryNumber
}
let option = document.querySelector('option:checked')
if (option !== options[0]) {
option.innerText = option.dataset.countryNumber
}
})
})
There's also a demo at CodePen
So I have select on my page and based on user choice I want to show that amount of input fields to him and then do something with it in php script.
It looks like this:
https://i.imgur.com/RlYySko.png
And if user chooses 3 then 3 input fields should appear if 2 then 2 etc. without reloading page. What should be used here any js or something?
Assuming you have an already existing form f, you could create the input elements dynamically by looping x times where x is the selected number of inputs required, so something like
for ( var i=0;i<x;i++){
var inputText = document.createElement("input"); //input element, text
inputText.setAttribute('type',"text");
inputText.setAttribute('name',"mark" + i);
f.append(inputText);
}
Here's a snippet, you can run and check it. It also preserves inputs values in case of number of inputs reduce.
var inputNumber = document.getElementById('input-number');
inputNumber.addEventListener('change', changeNumberOfInputs);
function changeNumberOfInputs(event) {
var desiredInputs = parseInt(event.target.value);
var inputsForm = document.getElementById('inputs-form');
var actualInputs = inputsForm.getElementsByTagName('input').length;
if(actualInputs < desiredInputs) {
for(var i=0; i<(desiredInputs - actualInputs); i++) {
inputsForm.appendChild(document.createElement('input'));
}
}
else if(actualInputs > desiredInputs) {
for(var i=0; i<(actualInputs - desiredInputs); i++) {
var lastInput = inputsForm.getElementsByTagName('input');
lastInput = lastInput[lastInput.length - 1];
inputsForm.removeChild(lastInput);
}
}
}
<select id="input-number">
<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>
</select>
<form id="inputs-form">
<input />
</form>
What you want to do, is to create all 6 of the Input fields. Then hide them all as standard, and do document.getElementById(id).style to get the style. Then call a function when the Select changes, and use the selected value to uncover the hidden inputs!
As #Arthur Cantarela stated, this is a bad practice in JS.
Alternatively, you could put them in a div, and change the div's innerHTML according to how many you need!
You could use ng-repeat in angularjs and bind the number select to the repeat expression.
I have set default value to an input box and set it to readonly.
I also disable some select options.
It is working but when I add another ID for another product, only 1 ID works.
Please note that I don't have access to the actual html pages. I can only access the js file.
What I need is:
if I go to product 1 OR product 2, I will see the text box is set to 28 in readonly and the Weeks/Months disabled.
Below is my sample HTMLs.
The HTMLs below are two different HTML pages.
HTML for product 1
<p>Deliver products every <input type="text" id="thisInput_prod1"></p>
<select id="thisSelect_prod1">
<option value="Days" selected>Days</option>
<option value="Weeks">Weeks</option>
<option value="Month">Month</option>
</select>
HTML for product 2
<p>Deliver products every <input type="text" id="thisInput_prod2"></p>
<select id="thisSelect_prod2">
<option value="Days" selected>Days</option>
<option value="Weeks">Weeks</option>
<option value="Month">Month</option>
</select>
This is the .js file
window.onload = SetDefaultValue;
function SetDefaultValue() {
document.getElementById('thisInput_prod1').setAttribute('value','28');
document.getElementById('thisInput_prod1').readOnly = true;
var x = document.getElementById('thisSelect_prod1');
x.options[1].disabled=true;
x.options[2].disabled=true;
//below is to set the other product - I disable because its not working
//document.getElementById('thisInput_prod2').setAttribute('value','28');
//document.getElementById('thisInput_prod2').readOnly = true;
//var y = document.getElementById('thisSelect_prod2');
//y.options[1].disabled=true;
//y.options[2].disabled=true;
}
When there's no thisInput_prod2 element, document.getElementById('thisInput_prod2') will evaluate to null, and then the code will abort trying to call .setAttribute on that null. You should assign it to a variable and test it to see if it's === null before dereferencing it.
Here is your working example : Fiddle
document.getElementById('thisInput_prod1').value = '28';
document.getElementById('thisInput_prod1').readOnly = true;
var x = document.getElementById('thisSelect_prod1');
x.options[1].disabled = true;
x.options[2].disabled = true;
document.getElementById('thisInput_prod2').readOnly = true;
var y = document.getElementById('thisSelect_prod2');
y.options[1].disabled=true;
y.options[2].disabled=true;
I have two dropdown lists that filter content. The first one is the locations and the second one is the jobs. The first list filters the second. I'm using a :contains to read the string values that allow my filter to work. I'm running into a problem when I want to use two contains at once as a filter. Here is the code:
HTML
<div class="holder">
<label for="volunteerLocation">Where do you want to volunteer?</label><br>
<select id="locations">
<option value="0">--Select a Campus--</option>
<option value="5">Location 1</option>
<option value="6">Location 2</option>
<option value="7">Location 3</option>
</select>
</div>
<br />
<div class="holder">
<label for="volunteerJobs">In which area would you like to serve?</label><br />
<select id="jobs">
<option value="1">Job 1 (Location 1)</option>
<option value="2">Job 2 (Location 2)</option>
<option value="3">Job 3 (Location 3)</option>
<option value="4">Job 4 (All locations)</option>
</select>
</div>
Javascript
var select = $('#jobs');
var options = [];
$(select).find('option').each(function () {
options.push({ value: $(this).val(), text: $(this).text() });
});
$(select).data('options', options);
$('#locations').change(function () {
filterText = $("#locations option:selected").text();
var optionList = $(select).empty().data('options');
var j = 0;
$.each(optionList, function (i) {
var option = options[i];
if (option.text.indexOf(filterText) !== -1) {
if (j == 0) {
$('#jobs').prepend("<option value=''>--Select a Job--</option>").val('');
j++;
};
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
if (filterText == "--Select a Campus--") {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
})
})
Here is a JSLint of this so you can see it in action Full Example
I'm trying to get "Job 4" to show up on everything but the "Select a Campus" option. How do I do that?
instead of looping with .each every time location change, and going through exceptions, me would create an index upon page load
var locJobs=new Array();
then you fill it with your data, for example
locJobs['5']=new Array();
locJobs['5'] = ['job 1','job 2']
then on change
$("#jobs").html('<option>'+locJobs[$(this).val()].join('</option><option>')+'</option>');
if you need to add the value on the options of #jobs you'll have to complicate that snippet a bit.
It shall be more efficient & also make maintenance much easier (no exceptions to deal with just an array to populate from whatever data source you are using) as you'll end up with a very flexible solution
nb: you declare var select = $("#jobs") but then you use $(select); that is a useless overhead use select directly
a convention to keep code clear is to add $ to any variable that is caching a jquery object :
var $select=$("#select")
then you use $select.whtever(//...
I want to ask quick question, i want to make a select drop down that when i choose one of the options the values of the other select drop down change ...
let's say i have select drop down called model that has the following
- Acura
- Aston martin
- Audi
I want when i choose (let's say ) Audi, in the type select drop down i find Audi type's only
- A3
- A5
- A4
I don't want to use AJAX calls, i just want to use javascript or jquery to filter the data
thanks guys
Like Shomz said,
Assuming the dropdowns look like this:
<!-- First dropdown. Make of car -->
<select name='Manufactor' id='make'>
<option value='null'>Select a Make</option>
<option value='Audi'>Audi</option>
<option value='BMW'>BMW</option>
<option value='Volvo'>Volvo</option>
</select>
<br />
<!-- Second dropdown. Model of car -->
<select name='Model' id='model'>
</select>
The javascript would look like this:
<script type='text/javascript'>
var model = ['','audi','bmw','volvo']; //Set makes
model[1] = ['A3', 'A5', 'A4']; // Set Audi models
model[2] = ['M3', 'M5', 'M6']; // Set BMW models
model[3] = ['C30', 'C70']; // Set Volvo models
var test = model[1][1];
function setModel(index) {
var modelDropdown = document.getElementById('model');
modelDropdown.options.length = null;
for(var i = 0; i < model[index].length; i++) {
modelDropdown.options[i] = new Option(model[index][i]);
}
}
window.onload = function() {
var makeDropdown = document.getElementById('make');
makeDropdown.onchange = function() {
setModel(this.selectedIndex);
}
}
</script>
Notice that the Models start at index 1 and not 0, because the first option is a blank Select Model option.
AJAX calls would still be the best solution, but if you don't want to use them, you can always manually create arrays for each of the main options, make an onchange event on the select element which would call the selected array and create another dropdown based on the elements of that array. Hope I didn't make it sound to complicated, since it isn't.
Here's a sample how to extract values with jQuery.