How to use two IDs from JS? - javascript

On my page with payment I need two inputs with total payment value:
- one that the client can see
- another one which is hidden.
I wrote a code which pass price of every element to the input when a client check a box with a product they want to pay for, but it works only with the one input.
I was trying to use different options (like getElementsByName and getElementsByClassName) but I am learning JS now and I have no idea how to solve this problem. :(
function select(selector, parent){
return Array.from((parent||document).querySelectorAll(selector));
}
var inputs = select('.sum'),
**totalElement = document.getElementById('payment-total');**
function sumUpdate(){
totalElement.value = inputs.reduce(function(result, input){
return result + (input.checked ? parseFloat(input.value) : 0);
}, 0).toFixed(0);
}
WHAT I TRIED:
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total')[0][1];**
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total, payment-total2')[0][1];**
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total).getElementsByName('payment-totalTwo);**

If I'm understanding you right, you want to put the computed value in both the id="payment-total" element and the id="payment-total2" element.
If so, just do what you've already done for payment-total, but for payment-total2 as well, see *** comments:
var inputs = select('.sum'),
totalElement = document.getElementById('payment-total'),
totalElement2 = document.getElementById('payment-total2'); // ***
function sumUpdate(){
//vvvvvvvvvvvvvvvvvvvvvv---- ***
totalElement2.value = totalElement.value = inputs.reduce(function(result, input){
return result + (input.checked ? parseFloat(input.value) : 0);
}, 0).toFixed(0);
}
I don't immediately see the reason for having both a visible and a hidden input, but if you need that for some reason, that's how you'd do it.
If it got to the point there were three or more elements you wanted to update, I'd probably give them all a class and select them the way you've selected your .sum elements, then compute the total once and assign it to all of them in a loop. But for just two, repeating the lookup and assignment seems fine.

Related

How can get last value of form charge in jQuery

I am trying to make a form where a customer can choose parson and automatically show the cost depend on parson number. So for that, I used jQuery form change function and calculate the cost inside of the function. My all logic is working ok but the issue is when increasing number then showing multiple costs.
Visual look:
Always I want to show the last one/ updated one
Blow my code:
var adultsSingleChage = 200;
var childrenSingleCharge = 100;
var infantsSingleCharge = 50;
$('#absbt_form input').change(function(){
var adults = $("#absbt_adults").val();
var adultsCharge = adults * adultsSingleChage;
var children = $("#absbt_children").val();
var childrenCharge = children * childrenSingleCharge;
var infants = $("#absbt_infants").val();
var infantsCharge = infants * infantsSingleCharge;
var totalCharge = adultsCharge + childrenCharge + infantsCharge;
console.log(totalCharge);
$('.total_cost').append(totalCharge);
});
I know I did the maximum of logic but for last logic, I'm confused.
How can I just show the last one?
append adds new content to existing one - that's the reason of having previous values.
Instead of using append use text:
$('.total_cost').text(totalCharge);
The problem is with the code you are appending which means you are adding the text into the element instead of replacing it. You can use the following two methods:
text(): $('.total_cost').text("iota")
html(): $('.total_cost').html("iota")
Note: Use id selector or with class use $($('.total_cost')[0])
Use html(totalCharge) instead of append(totalCharge)

Validating multiple fields in an HTML form using JS

I have a signup form which is having some 12 fields. I want to validate data in those fields. First step is to check if any field is empty. One way of doing this is to get each field using Jquery and check if it is empty. I was planning to create a var array and check status of each field inside a loop using this code :
var input = new Array();
input[0] = $('.fullName')[0];
input[1] = $('.emailID')[1];
input[2] = $('.phno')[2];
input[3] = $('.userName')[3];
input[4] = $('.password')[4];
input[5] = $('.batch')[5];
input[6] = $('.nickname')[6]
input[7] = $('.enrno')[7];
input[8] = $('.dob')[8];
input[9] = $('.fromCity')[9];
input[10] = $('.currcity')[10];
input[11] = $('.interests')[11];
input[12] = $('.currComp')[12];
input[13] = $('.currDesig')[13];
Now I have to run a loop to get the values and check if any field is blank.
I am writing this code for checking
for(i=0;i<14;i++)
if(input[i].val()=="")
{
// do my work
}
But the problem is that the last 15 lines of code are pointing to actual HTML DOM element, so I can't use input[i].val() directly to access the value. Any way out?
You seriously need to just add a common class to the elements that needs validation, and then do
var is_valid = $('.validate_these').filter(function() {
return $.trim(this.value) === "";
}).length === 0;
That gets all the elements with that class, and filters them based on wether or not the value is empty. If no empty elements where found, it's valid

adding radio button values in separate groups using javascript

I have a form with radio buttons that I'm using javascript to loop through and return the sum of all the radio buttons to an input element at the bottom of the page. The script I'm using is this and it works fine.
<script type="text/javascript">
function checkTotal() {
var radios = document.querySelectorAll('input[type=radio]'),
sumField = document.querySelector('input[type=text]');
var sum = 0;
for (var i = 0, len = radios.length - 1; i <= len; i++) {
if (radios[i].checked) {
sum += parseInt(radios[i].value);
}
}
sumField.value = sum;
}
</script>
Here's my form http://cognitive-connections.com/Prefrontal_Cortex_Questionnaire.htm
However I need to build another form where there are several questions in different groups and I need to sum the totals for each group separately and post them to their corresponding input elements on the page accordingly. Here's my new form http://cognitive-connections.com/Prefrontal_Cortex_Questionnaire100913.htm
I'm not an advanced javascript user but do have a pretty good understanding of programming itself (I think, lol) My head tells me that I should be able to simply declare a unique var for each different group and a unique element to post it's results to and use the same loop (with correct vars for each group) for each group. But when I add [name="elements name"] as the identifier for the document.querySelectAll it grabs the elements with that name only and if I name the elements themselves the same name the radio buttons loose their inherent property of only letting one radio button per question be selected at a time? I've also tried creating a class id for each group and tried to use it as the identifier in the document.querySelectAll and it doesn't seem to work at all then. Any help is greatly appreciated..
As per my understanding of question, below is my answer. And here is the fiddle http://jsfiddle.net/8sbpX/10/.
function enableQ(cls) {
var ele = document.querySelectorAll('.' + cls)[0],
ev = (document.addEventListener ? "#addEventListener" : "on#attachEvent").split('#');
ele[ev[1]](ev[0] + "change", function () {
var radios = ele.querySelectorAll('[type="radio"][value="1"]:checked').length;
ele.querySelector('[type="text"]').value = radios;
});
}
enableQ("rad-grp");

JavaScript Asp.net repeating controls

I am trying to do the folowing with Asp.net 3.5/IIS
A web form with a top level repeatable form. So basically a Order->Products->ProductsParts kinda of scenerio. Order is only one. Product is repeatable. Each product has repeatable products parts. The product and product part have a whole bunch of fields so I cannot use a grid.
So, I have add/remove buttons for Product and within each product add/remove buttons for each product part.
That is my requirement. I have been able to achieve add/remove after some research using jquery/js. How, do i capture this data on the server? Since javascript is adding and removing these controls they are not server side and I don't know how to assign name attributes correctly. I am trying following javascript but it ain't working:
function onAddProperty(btnObject){
var previous = btnObject.prev('div');
var propertyCount = jquery.data(document.body, 'propertyCount');
var newDiv = previous.clone(true).find("*[name]").andSelf().each(function () { $(this).attr("name").replace(($(this).attr("name").match(/\[[0-9]+\]/), cntr)); }); ;
propertyCount++;
jquery.data(document.body, 'propertyCount', propertyCount);
//keep only one unit and remove rest
var children = newDiv.find('#pnlUnits > #pnlUnitRepeater');
var unitCount = children.length;
var first = children.first();
for (i = 1; i < unitCount; i++) {
children[i].remove();
}
newDiv.id = "pnlPropertySlider_" + propertyCount;
newDiv.insertBefore(btnObject);
}
I need to assign name property as array so that I can read it in Request.Form
Fix for not updating ids not working:
var newDiv = previous.clone(true).find("input,select").each(function () {
$(this).attr({
'name': function () {
var name = $(this).attr('name');
if (!name) return '';
return name.replace(/property\[[0-9]+\]/, 'property' + propertyCount);
}
});
}).end().insertBefore(btnObject);
The issue looks like the following line:
$(this).attr("name").replace(($(this).attr("name").match(/\[[0-9]+\]/), cntr));
This statement doesn't do anything. Strings in JavaScript an immutable, and .replace only returns the string with something replaced.
You would then have to actually set the attr("name") to the new string that has the replaced value:
http://api.jquery.com/attr/
I can't help much more without seeing your HTML.

Getting value of selected checkbox with jquery from checkboxes without id's

I have a number of checkboxes that are generated from a JavaScript API call from a database. I need to be able to pass the values of the checkboxes which are then selected by the user, and sent to the processing page. The issue is that the checkboxes don't have ID's associated with them(or this wouldn't be a problem) They all have the same name, but no ID's.
What is the best way to find which check boxes are selected, and pass their values to the following page?
One way I started was with an array:
var options = ["option1","option2","option3"];
var option 1 = [0];
var option 2 = [1];
var option 3 = [2];
On the processing page, using:
var option1 = getFromRequest('option1') || '';
var option2 = getFromRequest('option2') || '';
var option3 = getFromRequest('option3') || '';
Is there a better way of doing this?
I've changed the implementation to the following:
var values = []
$("input:checkbox.subIndustry").each(function(){
values.push(this.value);
});
passing the values to the success page with
window.location.href = REGISTER_SUCCESS +'&values='values.join(",")
which should then get the value with
var variablname = getFromRequest('values') || "";
This is returning Undefined. Any help?
An easy way to select them would be something like $("input[type=checkbox]:checked")
However, if you wanted to keep up with them as they are checked, even if they are added after you load, you could create a variable, then asign a delegation to the "change" state of each input that is a checkbox and update this variable on each change.
It's as simple as:
var checked, checkedValues = new Array();
$(function() {
$(document).on("change", "input[type=checkbox]", function(e) {
checked = $("input[type=checkbox]:checked");
// if you wanted to get an array of values of the checked elements
checkedValues = checked.map(function(i) { return $(this).val() }).get();
// make a string of the values as simple as joining an array!
var str = checkedValues.join(); // would return something like: value1,value2,ext...
});
})
Working Example
Since all your checkboxes have the same name, you can retrieve the checked ones using a variation of:
var checked = $('input[name=ckboxname]:checked');
see: :checked selector for more information
you can simply get the values of checked checkboxes by using
$('input[name=checkboxname]:checked').val();
this will give you the value of checkbox which is checked and for all values simply use
each function of jquery.
Turns out, the answer was to utilize indexOf in the underscore.js library. The solution had to be applied in the API being used to send data.
(_.indexOf(values, '9') != -1 ? 1 : '0'),

Categories

Resources