issue with change function on select option in Jquery - javascript

I have a little select form. When I change options using JQUERY, new suitable price appears inside .prices. AN old price is 100 $. if user is student or pupil, I want make him discount -10 $. So when user choose option student or pupil price is changed from 100 to 90$. But when user choose option again to pupil it must not be change the price, but it changes it to 80 $. Again when choose option student, price was changed to 70. I exactly want that if user choose option: student or pupil, there will be -10 $ discount.
you can ask why I used each function? The option: other is selected and first time page shows price 110$. each function fixed this problem. I have also JS fiddle, you can check it.
Sorry for my English Language.
DEMO
HTML
<select name="status" id="status">
<option value="1">Student</option>
<option value="2">Pupil</option>
<option value="3" selected>Other</option>
</select>
<div class="price">
<span class="prices">100</span> $
</div>
JQUERY
$( "#status" ).change(function () {
var price2 = ($(".prices").text());
$('.prices').text('');
var value = $( "#status option:selected" ).val();
if(value=="3")
{
new_price2 = +price2 + +10;
$('.prices').append(new_price2);
}
else
{
new_price2 = price2 - 10;
$('.prices').append(new_price2);
}
})
.change();
$('#status option').each(function() {
if(this.selected)
{
var price2 = ($(".prices").html());
$('.prices').html('');
new_price2 = price2 - 10;
$('.prices').append(new_price2);
}
});

You only need the change handler in your jQuery code. Also, you need to keep a static base price value so that you can do all calculations on that instead of keeping a running total of all changes. Try this:
$("#status").change(function () {
var price2 = $(this).data('base-price');
if ($("option:selected", this).val() == "3") {
new_price2 = price2;
} else {
new_price2 = price2 - 10;
}
$('.prices').text(new_price2);
}).change();
Example fiddle

Try this:
$( "#status" ).change(function () {
var price2 = ($(".prices").text());
$('.prices').text('');
var value = $( "#status option:selected" ).val();
if(value=="3"){
new_price2 = price2;
}
else{
new_price2 = price2 - 10;
}
$('.prices').html(new_price2);
})
DEMO here.

Related

form select option dynamic attr

I need to make Select name with option value, to select a specific value or index. the data where comes from db in a value "{{design}}".
I do get the value currectly, but I dont manage to set "selected" on the currect option value.
here is the code:
console.log("{{design}}");
$(document).ready(function () {
var options = $('select').children('option');
var size = $('select').children('option').length;
for (i=0;i<size;i++)
{
if ( options[i].innerHTML==="{{design}}")
{
options.selectedIndex=i;
}
}
});
the html is :
<select name="design" required id="design" >
<option value="1">flowers</option>
<option value="2">classic</option>
<option value="3">roses</option>
</select>
I need to make to currect {{design}} value, lets say it's 2, so it will be <option value="2" selected>classic</option>`
thanks!
SOLVED
Hi, found the solution to the issue, if anyone eles goes into trouble.
$(document).ready(function () {
var options = $('select').children('option');
var size = $('select').children('option').length;
for (i=0;i<size;i++)
{
if ( $('select').children('option')[i].value === "{{design}}")
{
$('select').children('option')[i].selected=true;
}
}
});
the currect way is to find the right option value and then-> [i].selected=true
goodluck
Try this
var selectedvalue=2; //option with value 2 should be selected
$("#design option[value=selectedvalue]").attr("selected","selected");
Hope this helps...
If I understood right, you are on the right path just taking a minor detour. Try this:
if ( options[i].innerHTML==="{{design}}")
{
options.attr('selected', 'selected');
}
The example of .each() usage:
$(document).ready(function(){
$('select option').each(function(i){
if( i.value === "{{design}}"){
$(this).attr('selected','selected');
}
});
});
try this:
$(document).ready(function(){
$('select option').each(function(i){
//if this option contains the word "{{design}}" Then this is selected
if( $(this).html().indexOf("{{design}}") != -1)
$(this).attr('selected',true);
});
});

jQuery dynamic created input sum and subtract on select option

i'm working with jquery and need help to calculate the values of input depended on select option inserted dynamically.
i want if select value is debit it will subtract from selected credit value and difference show in id diff as i inserted more ows all values calculate by debit and credit.
<table class="vtable">
<tr>
<td>Type</td>
<td>Amount</td>
</tr>
<tr>
<td>
<select name="type" id="type">
<option>-type -</option>
<option value="debit">debit</option>
<option value="credit">credit</option>
</select>
</td>
<td><input type="text" id="amount"></td>
</tr>
</table>
My fiddle demo is below
Demo
Thanks
DEMO
Try this
$(document).on('change', 'select', function () {
var value = $(this).val();
var input = $(this).parents('td').next('td').find('input:text');
if (value == 'debit') {
total -= parseInt(input.val());
} else if (value == 'credit') {
total += parseInt(input.val());
}
$('#diff').html('Differance:' + total);
});
Hope this helps,Thank you
$('select#type').on('change', function() {
if($(this).val() === "debit"){
//Get the difference between 2 variables and store result in diff
$("#diff").val(Math.abs(a - b))
}else if($(this).val() === "credit"){
//perform addition and store value in sum object
$("#sum").val(x+y)
}
});
what about something like this?
$('select[name="type"]').change(function()
{
if($(this).val() === 'credit')
{
$("#amount").val() += $('input[type="text"]').val()
}
else if($(this).val() === 'debit')
{
$("#amount").val() -= $('input[type="text"]').val()
}
})
I use the the change() function to trigger the change.
I don't know if this is what you meant, but i hope it helped somehow.
one issue corrected in more button click handlers. see the changes below:
$("#more").click(function() {
$(".vtable tr:last").clone().find("input, select").each(function() {
$(this).attr({'id': function(_, id) { return id + 1 }});
}).end().appendTo(".vtable");
});
in order to handle the events for dynamically added select and input text, you can achieve it as follows.
Note: .on() is used with your table as your are adding rows dynamically with select and input text.
for select :
$('.vtable').on('change', "select", function (e) {
var valueSelected = this.value;
alert(valueSelected);
});
for input text
$('.vtable').on('keyup', "input", function (e) {
var valueEntered = this.value;
alert(valueEntered );
});

Change to plural if value in textbox is greater than 1

I have a textbox and a selectbox like this:
<h3>Recipe Yield</h3>
<input style='width:100px' type="text" name="yield" class="small" />
<select name='yieldType'>
<option value='Servings'>Serving(s)</option>
<option value='Cups'>Cup(s)</option>
<option value='Loaves (Loaf)'>Loaves (Loaf)</option>
</select>
Here's a JSFiddle: http://jsfiddle.net/T3Sxb/
As you can see, the select options are in the form of word(s)
but I want to have a script where when
If the number in the inputbox is 1, the value in the options are in the form of word
If the number in the inputbox is greater than 1, the value in the options are plural.
Is this possible? How can I do this? Thanks for all help!
Demo: http://jsfiddle.net/T3Sxb/8/
Alternate using input[type="number"]: http://jsfiddle.net/T3Sxb/15/
Multiple inputs, styled: http://jsfiddle.net/T3Sxb/17/
I'm using data attributes so that you can declare the proper singular/plural forms for each item. Simply adding "s" doesn't work in many cases.
Also note that zero items usually (always?) takes a plural form.
HTML
<input style='width:100px' type="text" id="yield" class="small" />
<select id='yieldType'>
<option value='Servings' data-single="Serving" data-other="Servings"></option>
<option value='Cups' data-single="Cup" data-other="Cups"></option>
<option value='Loaves (Loaf)' data-single="Loaf" data-other="Loaves"></option>
</select>
JavaScript
var yield = $("#yield");
var yieldType = $("#yieldType");
function evaluate(){
var single = parseInt(yield.val(), 10) === 1;
$("option", yieldType ).each(function(){
var option = $(this);
if(single){
option.text(option.attr("data-single"));
}else{
option.text(option.attr("data-other"));
}
});
}
// whatever events you want to trigger the change should go here
yield.on("keyup", evaluate);
// evaluate onload
evaluate();
You could try this: http://jsfiddle.net/T3Sxb/7/
var plural = {
Serving: "Servings",
Cup: "Cups",
Loaf: "Loaves"
};
var singular = {
Servings: "Serving",
Cups: "Cup",
Loaves: "Loaf"
};
$( "#pluralizer" ).on( "keyup keydown change", function() {
var obj = parseInt( $( this ).val() ) === 1 ? singular : plural;
$( "#YieldType option" ).each( function() {
var html = $( this ).html();
if ( html in obj ) {
$( this ).html( obj[html] );
}
});
});
From a UX point of view, I think (s) is perfectly acceptable. But anyway, how about this:
<option value='Servings' data-singular="Serving" data-plural="Servings">Servings</option>
then:
// you should really use IDs ;)
$('input[name="yield"]').on('change', function () {
var singular = parseInt($(this).val(), 10) === 1;
$('select[name="yieldType"]').each(function () {
if (singular) {
$(this).val($(this.attr('data-singular')));
} else {
$(this).val($(this.attr('data-plural')));
}
});
});

How to add dynamically a combobox using jQuery

I've this working code which is creating one combobox:
You can see it working here: jsfiddle
$('body').on('change', '.combo', function() {
var selectedValue = $(this).val();
if ($(this).find('option').size() > 2) {
var newComboBox = $(this).clone();
var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
var newComboBoxIndex = thisComboBoxIndex + 1;
$('.parentCombo' + thisComboBoxIndex).remove();
if (selectedValue !== '') {
newComboBox.attr('data-index', newComboBoxIndex);
newComboBox.attr('id', 'combo' + newComboBoxIndex);
newComboBox.addClass('parentCombo' + thisComboBoxIndex);
newComboBox.find('option[val="' + selectedValue + '"]').remove();
$('body').append(newComboBox);
}
}
});
Which is resulting something this, everytime I fill a combobox, the next one is opened.
How can I change that code to have this? Which means two comboboxes opening (please forget the style)
Thank you.
I'm not entirely sure if your intent, but it seems like you want to have groups of two select elements and then adding a new group when the user selects a value.
In that case I suggest grouping your two selects in a fieldset like this:
<fieldset>
<select id="combo1" class="combo" data-index="1">
<option></option>
<option val="Opt1">Opt1</option>
<option val="Opt2">Opt2</option>
<option val="Opt3">Opt3</option>
</select>
<select id="combo2" class="combo" data-index="2">
<option></option>
<option val="Opt1">Opt1</option>
<option val="Opt2">Opt2</option>
<option val="Opt3">Opt3</option>
</select>
</fieldset>
​
And then looking up that parent fieldset and cloning it like this:
$('body').on('change', '.combo', function() {
var selectedValue = $(this).val();
var fieldset = $(this).parents('fieldset');
if ($(this).find('option').size() > 2) {
var newFieldset = fieldset.clone();
var newComboBox = $(fieldset).children('.combo:first');
var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
var newComboBoxIndex = thisComboBoxIndex + 1;
$('.parentCombo' + thisComboBoxIndex).remove();
if (selectedValue !== '') {
newComboBox.attr('data-index', newComboBoxIndex);
newComboBox.attr('id', 'combo' + newComboBoxIndex);
newComboBox.addClass('parentCombo' + thisComboBoxIndex);
newComboBox.find('option[val="' + selectedValue + '"]').remove();
$('body').append(newFieldset);
}
}
});​
There are some details probably not exactly the way you need it, but in general this is the approach I'd recomment.
Find the updated Fiddle here: http://jsfiddle.net/JaVVe/8/
If you just want to double the amount of combo boxes you could use a for-loop and set their values depending on the value of the counter-variable.

How do i manipulate select box using jquery?

I have some select boxes like the following:
<select id="my_box1" rel="cal_10">
<option value="A"></option>
</select>
<select id="my_box2" rel="cal_10.50">
<option value="A"></option>
</select>
....
<select id="my_boxn">
<option value="B"></option>
</select>
On changing, I want to add the related value (that is 10 and 10.50) only when the select boxes has the same option value.
For Example: if the first and second select box has option value as A, then I want to add it.
How can I do this using jQuery?
Well, I really can't tell exactly what you're asking, so I'll just guess.
I'm guessing that when a select element receives a change event, we should find all other selects where the selected value is the same, and sum the numeric portion of the rel attribute.
If so, you can do this:
var boxes = $('select[id^="my_box"]');
boxes.on('change', function() {
var n = 0,
val = this.value;
boxes.each(function() {
if( this.value === val ) {
n += +$(this).attr('rel').replace('cal_','');
}
});
alert( n );
});
If you're using a version of jQuery older than 1.7, then use boxes.bind instead of boxes.on.
Something like this, I believe:
$(function() {
$('select#my_box1, select#my_box2').bind('change', function() {
if ($('select#my_box1').val() == $('select#my_box2').val())
$('select#my_box2').append('<option value="10">10</option><option value="10.50">10.50</option>');
else $('select#my_box2').find('option[value="10"], option[value="10.50"]').remove();
});
});
I tried by below code,
$('select').change(function(){
var totalWeight = 0;
var post_array = [];
var actual_val = value;
//alert(actual_val);
var x=0;
$("select").each(function(index, selectedObj) {
current = $(this).val();
var combined = $(this).attr('rel');
if(combined!=undefined)
{
combined = combined.split("_");
var is_combined = combined[0];
var combined_pid = combined[1];
if(actual_val == current && is_combined == "cal"){
post_array[x++] = combined_pid ;
totalWeight+=parseFloat(combined_pid);
}
}
});
alert(totalWeight);
});
I will get my total value in totalWeight

Categories

Resources