Javascript select option keeps showing a '0' before value - javascript

I'm having an issue with getting the value of a select option and calculating it, the issue is that everytime i select an option a random '0' keeps being displayed before it. Any help would be appreciated, here is the relevant code:
<div class="otherCars">
<label for="otherCars">Do you drive any other cars?</label>
<select name="otherCars" class="style1" id="carsSelect" onchange="getQuote()" onblur="validateSelect('cars')" >
<option value="empty">-Please select-</option>
<option value="10" id="car1">No access to any other cars </option>
<option value="20">Own another car</option>
<option value="100">Named driver on another policy</option>
<option value="100">Company car (including personal use)</option>
<option value="100">Company car (excluding personal use)</option>
</select>
</div><!-- Closing div tag-->
Javascript:
function getQuote(){
var disqualifiedDifference = 0;
var genderDifference = 0;
var carDifference = 0;
var menuSelect = document.getElementById("carsSelect");
var carValue = menuSelect.options[menuSelect.selectedIndex].value;
function genderPrice(){
if (document.getElementById("male").checked){
genderDifference += 200;
}
if (document.getElementById("female").checked){
genderDifference += 175;
}
}
function disqoPrice(){
if (document.getElementById("yes").checked){
disqualifiedDifference += 300;
}
if (document.getElementById("no").checked){
disqualifiedDifference += 0;
}
}
function carPrice(){
if (document.getElementById("car1").selected){
carDifference += 200;
}
if (document.getElementById("car2").selected){
carDifference += 20;
}
}
genderPrice();
disqoPrice();
var totalPrice = disqualifiedDifference + genderDifference + carDifference + carValue;
document.getElementById('totalPrice').innerHTML = totalPrice;
} //end of CalculateTotal

menuSelect.options[menuSelect.selectedIndex].value returns a string, which means that the + operator will be performing string concatenation rather than addition. Cast the value to a Number before trying to do arithmetic.
var carValue = +menuSelect.options[menuSelect.selectedIndex].value;
// ^ unary + operator casts a string to a number

Related

The scripts that I made dont work and I can't find the problem

First of all, sorry, I know the next code is wrong, I'm new in programming and I have a problem with it. When the user select an option from the Select, a value it must change, then, the user must write a price in numbers which value must not be higher than the previous value, here is when the scripts should act but it doesn't works. The correct code must be something like that:
<script>
function cboc(){
var cb = $("#cbotipfon").val();
var maxvalGORE = null;
if(cb == 0){
maxvalGORE = 0;
if(cb == 15){
maxvalGORE = 100;
}
if(cb == 16){
maxvalGORE = 200;
}
}
function cbocc(){
var val = null;
var x = document.GetElementById('txtprepos').value;
val = parseInt(x);
if(val > maxvalGORE){
alert('The value is higher than $' + maxvalGORE +'.');
document.GetElementById('txtprepos').value = "";
}
}
</script>
<select style="width=5.5em;" name="cbotipfon" id="cbotipfon" onchange="cboc()">
<option value="0">Select</option>
<option value="15">Option A</option>
<option value="16">Option B</option>
</select>
<input type="number" onblur="cbocc()" name="txtprepos" id="txtprepos"/>
I've been with that problem for days. If you can help me I'll be eternally grateful. Thanks in advance and for take your time.
Here is a simple example. No need to declare any function. Just declare your variables correctly and use the addEventListener method for getting the values of the input and select elements.
var maxvalGORE ,val ,cb ,x = null;
document.getElementById("cbotipfon").addEventListener("change", function(){
var cb = document.getElementById('cbotipfon').value;
if(cb == 0){
maxvalGORE = 0;
}
if(cb == 15){
maxvalGORE = 100;
}
if(cb == 16){
maxvalGORE = 200;
}
});
document.getElementById("txtprepos").addEventListener("change", function(){
x = document.getElementById('txtprepos').value;
val = parseInt(x);
if(val > maxvalGORE){
alert('The value is higher than $' + maxvalGORE +'.');
} else if(val == maxvalGORE) {
alert('The value is equal to $' + maxvalGORE +'.');
} else {
alert('The value is lower than $' + maxvalGORE +'.');
}
document.getElementById('txtprepos').value = "";
});
<select style="width=5.5em;" name="cbotipfon" id="cbotipfon">
<option value="0">Select</option>
<option value="15">Option A</option>
<option value="16">Option B</option>
</select>
<input type="number" name="txtprepos" id="txtprepos"/>

How can i take value from input select type and use it in javascript?

So I have this project where I have to make a clothing store and I want to do the following:
I have this code in html:
<select class="sizeb" style="display: none;">
<option value="xxs">XXS</option>
<option value="xs">XS</option>
<option value="s">S</option>
<option value="m">M</option>
<option value="l">L</option>
<option value="xl">XL</option>
<option value="xxl">XXL</option>
</select>
and with JavaScript I want to take the option value, check it's value and create a var price; then check and set a price:
var x = <somehow to get the value>;
if (x == 'xxs')
price = 5;
else if(x == 'xs')
price = 10;
and display it later this way:
document.getElementById("PriceTag").innerHTML = "Pret: " + price + " RON";
Any help is appreciated.
First, you just get a reference to the HTML element and assign that to a variable:
var select = document.querySelector(".sizeb");
Then you get the value:
var val = select.value;
Then you do your logic and calculations:
var x = <somehow to get the value>;
if (x == 'xxs'){
price = 5;
} else if(x == 'xs') {
price = 10;
}
And, then display the result:
document.getElementById("PriceTag").innerHTML = "Pret: " + price + " RON";
NOTE: You have your select to be hidden initially. If that's the case, no one will ever be able to select a value from it.
Now, you also have to decide "when" you want all this to be done. That could be when the value in the select changes. BUt, if that's the case, you should add a first option of something like --- Select One ---, because if the user wants the first selection, they won't do anything, which won't trigger the change event. So, putting it all together, we get:
// Get a reference to the select
var select = document.querySelector(".sizeb");
// Set up an event handler that runs when the value in the select changes:
select.addEventListener("change", function(){
// Then you get the value:
var x = select.value;
var price = null;
// Then you do your logic and calculations.
// And if will work, but for this a switch is better
switch (x) {
case 'xxs' :
price = 5;
break;
case 'xs' :
price = 10;
break;
case 's' :
price = 15;
break;
case 'm' :
price = 20;
break;
case 'l' :
price = 25;
break;
case 'xl' :
price = 30;
break;
case 'xxl' :
price = 35;
break;
}
document.getElementById("PriceTag").innerHTML = "Pret: " + price + " RON";
});
<select class="sizeb">
<option value="">--- Select One ---</option>
<option value="xxs">XXS</option>
<option value="xs">XS</option>
<option value="s">S</option>
<option value="m">M</option>
<option value="l">L</option>
<option value="xl">XL</option>
<option value="xxl">XXL</option>
</select>
<div id="PriceTag"></div>
You can:
1-Add an listener to the select like this
<select onchange="someFunction(this)" class="sizeb" style="display: none;>
2-create a function like this:
function someFunction(element){
va price = element.value;
document.getElementById("PriceTag").innerHTML = "Pret: " + price + " RON";
}

I want to have a dropdown menu where you choose the number instead of the variable

the "var aantal = 10" gives me 10 traingles but I would like the user to insert their own amount of triangles.
var aantal = 10;
var triangle = [];
for (var i = 0; i < aantal; i++){
triangle[i] = new Triangle;
triangle[i].xLeft = 20 + 30*i;
triangle[i].yLeft = 20 + 20*i;
}
A quick and easy way to ask for user input in a browser is via the Window.prompt method.
This stops your code until the user presses "OK" or "Cancel" in a popup window. When the user fills in a value and presses "OK", the value is returned as a string. Here's an example:
var userInput = prompt("How many triangles do you want?", 10);
var count = parseInt(userInput, 10);
for (var i = 0; i < count; i += 1) {
console.log("Triangle " + i);
}
Note that you need to explicitly convert the string to a number. Additionally, you might want to check for null or NaN: when a user presses "Cancel" or fills in invalid data, you'll need to have a fallback.
Once this works, you might want to try to create an <input type="number"> HTML element and get your data from there.
I think Bas is asking for a html drop down list that triggers a function, something like this:
<!-- /JavaScript code-->
<script>
function setTriangles(value) {
var aantal = eval(value);//evaluate the input as it's coming as a string
if (aantal == 0) { //do nothing if the user has picked the description "Select number of triangles" in the drop down
return;
}
var triangle = [];
for (var i = 0; i < aantal; i++) {
triangle[i] = new Triangle;
triangle[i].xLeft = 20 + 30 * i;
triangle[i].yLeft = 20 + 20 * i;
}
}
</script>
<!-- /end of JavaScript code-->
<!-- /HTML code-->
<select id="input" onChange="setTriangles(this.value);">
<option value="0">Select number of triangles</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
<!-- /end of HTML code-->

javascript function freezing my browser

i have two select object one with begining time and one with ending time.
when i select for example 11:00 in begining time i want that all options before 11:00 in ending time bee disabled 11:15 selected and rest options selectable.
Also i want to say that i am newbie with javascript.
This is part of my HTML code:
<select id="rbaslasaat" onchange="bitissaati(1384581600, 1384586100);">
<option value="1384581600">10:00</option>
<option value="1384582500">10:30</option>
<option value="1384583400">11:00</option>
<option value="1384584300">11:30</option>
<option value="1384585200">12:00</option>
<option value="1384586100">12:30</option>
</select></div>
<select id="rbitirsaat">
<option id="saatb1384581600" value="1384581600" disabled="">10:00</option>
<option id="saatb1384582500" value="1384582500" disabled="">10:30</option>
<option id="saatb1384583400" value="1384583400" disabled="">11:00</option>
<option id="saatb1384584300" value="1384584300" disabled="">11:30</option>
<option id="saatb1384585200" value="1384585200" disabled="">12:00</option>
<option id="saatb1384586100" value="1384586100" disabled="">12:30</option>
</select></div>
and this is my JavaScript function:
function bitissaati(saata, saatb) {
var saata, saatb, saatc, saatca, sec, i;
saatc = document.getElementById('rbaslasaat');
saatca = saatc.options[saatc.selectedIndex].value;
sec = parseInt(saatca) + 900;
for (i = saata; i<= saatb; i + 900) {
if(i <= saatca ) { document.getElementById('saatb'+i).disabled=true; }
else { document.getElementById('saatb'+i).disabled=false; }
}
document.getElementById('saatb'+sec).selected=true;
}
i could not figured out what the problem is.
each time i try function my browser is freezing.
Thank you all for trying to help
get your code fixed:
for ( i = saata; i<= saatb; i += 900) {
edit: removed the var
I'd just do :
function bitissaati(elem) {
var opt = document.getElementById('rbitirsaat').getElementsByTagName('option'),
val = elem.value;
for (i=opt.length; i--;) {
opt[i].disabled = opt[i].value <= val;
}
}
FIDDLE
Replace the loop with this
for (var k = saata; k<= saatb; k += 900) {
if (k <= saatca) {
document.getElementById('saatb'+k).disabled=true;
}
else {
document.getElementById('saatb'+k).disabled=false;
}
}

jQuery: create multiple input fields on the basis of how many we select

I need to create input fields on the basis of which number was chosen from select menu,
like this code:
<select id="inputs" style="width:60px;">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
When we select 10, input fields will increase to 10 at the same time, When I select 2, it doesn't decrease from 10 to 2 :(
I think the best way might be to use replace() with a loop; unfotunately I couldn't get a solution.
$(document).ready(function() {
var scntDiv = $('#add_words');
var wordscount = 0;
var i = $('.line').size() + 1;
$('#inputs').change(function() {
var inputFields = parseInt($('#inputs').val());
for (var n = i; n < inputFields; ++ n){
wordscount++;
$('<div class="line">Word is ' + wordscount + '<input type="text" value="' + wordscount + '" /><a class="remScnt" href="#">Remove</a></div>').appendTo(scntDiv);
i++;
}
return false;
});
// Remove button
$('#add_words').on('click', '.remScnt', function() {
if (i > 1) {
$(this).parent().remove();
i--;
}
return false;
});
});
​
Could you help me please?
Try
$(function(){
$('#inputs').change(function(){
for(i=0; i < $("select option:selected").text; i++)
{
$('#divIdHere').append('<input blah blah />');
}
})
});
obviously change to suit :)
I realise that you already accepted an answer for this question, but I wasn't content to just leave the question as-is. Also: I was a little bored. Make of that what you will...
So! Here's my (belated) answer.
The benefits of my approach, or the reasoning behind it, are:
You can use the select to remove, and add, rows.
When removing rows using the select to remove rows it first removes those lines with empty inputs, and then removes whatever number of filled in input-containing rows from the end.
It allows you to use the .remScnt links as well.
Hopefully this is of some, even if only academic, use or interest to you:
function makeRow() {
var div = document.createElement('div'),
input = document.createElement('input'),
a = document.createElement('a');
t = document.createTextNode('remove');
div.className = 'line';
input.type = 'text';
a.href = '#';
a.className = 'remScnt';
a.appendChild(t);
div.appendChild(input);
div.insertBefore(a, input.nextSibling);
return div;
}
$('#inputs').change(
function() {
var num = $(this).val(),
cur = $('div.line input:text'),
curL = cur.length;
if (!curL) {
for (var i = 1; i <= num; i++) {
$(makeRow()).appendTo($('body'));
}
}
else if (num < curL) {
var filled = cur.filter(
function() {
return $(this).val().length
}),
empties = curL - filled.length,
dA = curL - num;
if (empties >= num) {
cur.filter(
function() {
return !$(this).val().length;
}).parent().slice(-num).remove();
}
else if (empties < num) {
var remainder = num - empties;
cur.filter(
function() {
return !$(this).val().length;
}).parent().slice(-num).remove();
$('div.line').slice(-remainder).remove();
}
}
else {
var diff = num - curL;
for (var i = 0; i < diff; i++) {
$(makeRow()).appendTo($('body'));
}
}
});
$('body').on('click', '.line a.remScnt', function() {
console.log($(this));
$(this).parent().remove();
});​
JS Fiddle demo.
Please note that I've made little, or (more precisely) no, attempt to ensure cross-browser usability with this. The native DOM methods used in the makeRow() function are used for (minor optimisations of increasing the) speed, using jQuery (with its cross-browser-abstractions might make things even more reliable. And is worth considering.
References:
Native vanilla JavaScript:
node.appendChild().
document.createElement().
document.createTextNode().
element.className().
node.insertBefore().
jQuery stuff:
appendTo().
change().
filter().
parent().
slice().
:text selector.
val().
okay change it a little to allow for a new list to be created.
$(function(){
$('#inputs').change(function(){
$('#divIdHere').empty()
for(i=0; i < $("select option:selected").text; i++)
{
$('#divIdHere').append('<input blah blah />');
}
})
});
that will basically empty out the contents of the div before adding them all back in again :)
you need to make you DIV before use append
just try this html
<select id="inputs" style="width:60px;">
<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="add_words"></div>
and Jquery with this importand line scntDiv.empty();
JQuery
$(document).ready(function() {
var scntDiv = $('#add_words');
var wordscount = 1;
var i = $('.line').size() + 1;
$('#inputs').change(function() {
var inputFields = parseInt($('#inputs').val());
scntDiv.empty()
for (var i = 0; i < inputFields; i++){
scntDiv.append($('<div class="line">Word is ' + wordscount + '<input type="text" value="' + wordscount + '" />'));
}
});
});
​
You could only add new lines to make up the number of lines when the select's value increases and only remove the 'extra' lines when it decreases.
$( document ).ready(
function() {
var divs = $( 'div#add_words' );
$( '#inputs' ).change(
function(evt) {
var n = $( this ).val();
var lines = $( 'div.line' );
var numlines = lines.size();
if( n > numlines ) {
// We want more line. Add some.
while( n > numlines ) {
numlines += 1;
divs.append( '<div class="line">Line ' + numlines + '</div>' );
}
}
else {
// Remove everything after the n'th line.
lines.slice( n ).remove();
}
} )
.change();
} );

Categories