jquery how get and makes array of input classes value - javascript

I have numbers of input with same classes, now I want to create an array based on it but I don't have any idea. This will not use the name tag of the input. this is my html code:
<input type="text" class="option" value='1'>
<input type="text" class="option" value='2'>
<input type="text" class="option" value='3a'>
...
<input type="text" class="option" value='43'>
<input type="text" class="option" value='6y'>
this will be multiple that I cannot determine the exact number of the input fields.
Now I want to create in jquery or javascript array to get those value but I dont have any idea.
I tried this code but only gets the last input value and not all the value.
var arrs = [];
jQuery('.option').each(function(){
arrs.push(jQuery(this).val());
});
var arrayLength = arrs.length;
var retval = "";
for (var i = 0; i < arrayLength; i++) {
retval = arrs[i] + '|';
//Do something
}
alert(retval);

You get the last value becuase
retval = arrs[i] + '|';
you replace your string everytime
try like this
retval += arrs[i] + '|';
You don't need loop to join
try like this
var retval = arrs.join("|");
alert(retval)

http://jsfiddle.net/ru3ymvc5/2/
retval = arrs[i] + '|';
This should be
retval += arrs[i] + '|';
Adding the + operator makes sure the previous values are not overwritten with the last value.
You could also avoid the loop entirely by using the join method of Array;
var retval = "";
retval = arrs.join("|");
Working JS Fiddle

Related

HTML form passing array of options as the values to the checklist

I'd like to figure a way out using html and javascript. I have a form which will get modified each week and would like to simplify editing it.
events_in = ["event_1_date", "event_2_date", etc...]
and would display the check boxes
[] event_1_date
[] event_2_date
which you can then use the form normally.
The array input to form values will get updated weekly with new events.
There is a way using php but couldn't translate it into the languages I want to use.
Using jQuery (as you have included the jQuery tag).. First add a div to your form:
<div id="checkboxes"></div>
Then in javascript:
$(function() {
var events_in = ["event_1_date", "event_2_date"],
events_in_count = events_in.length,
i = 0;
for(;i<events_in_count;i++) {
$('#checkboxes').append('<label><input type="checkbox" name="' + events_in[i] + '">' + events_in[i] + '</label>');
}
});
You could try something like this.
var one = "text here";
var two = "text here"
var array = [["one", one],["two",two]]
window.onload = init;
function init(){
var checkListItems = document.querySelectorAll(".checklist-items");
for(var i = 0; i < checkListItems.length; i++){
updateHTML(checkListItems[i]);
}
}
function updateHTML(item){
var id = item.getAttribute("id");
alert(id)
for(var i = 0; i < array.length; i++){
if(array[i][0] == id){
item.innerHTML = array[i][1];
}
}
}
<form action="">
<input type="checkbox"><span class="checklist-items" id="one">Item</span>
<input type="checkbox"><span class="checklist-items" id="two">Item</span>
<input type="checkbox"><span class="checklist-items" id="three">Item</span>
<input type="checkbox"><span class="checklist-items" id="four">Item</span>
<input type="checkbox"><span class="checklist-items" id="five">Item</span>
</form>

Incrementing int by check marking a radio button

I have a whole bunch of radio buttons formatted in the following way;
<input type="radio" name="Xch" value="XCheese " onclick="incrementIndex()">XCheese<br>
and my incrementIndex() function is simple enough;
var index = 0;
function incrementIndex() {
index += 1;
document.getElementById("demo").innerHTML = ""+index+"";
if ($("#Xch").attr("checked") == true){
index = 10;
}
}
And when a radiobutton is clicked it increments the index, but I want it to increase the index once and only if the button is not checked, the way it is set up, even if the Xch radio button is checked, it keeps increment the index! Please help.
Not sure why you would want to do something like this, but is this what you were trying to do?
<input type="radio" name="ch" value="XCheese " onclick="incrementIndex(this)">XCheese</input><br>
<input type="radio" name="ch" value="YCheese " onclick="incrementIndex(this)">YCheese</input><br>
<input type="radio" name="ch" value="ZCheese " onclick="incrementIndex(this)">ZCheese</input><br>
var index = 0;
var previousValue;
function incrementIndex(e)
{
if(e.checked && e != previousValue) index += 1;
previousValue = e;
alert(index);
}
Here's an example
http://jsfiddle.net/Md8fj/134/
What you're doing isn't exactly clear, but if you want the desired behavior, move the index += 1 inside the if statement that detects if it's already checked. If it's not, then you can increment.
Something like:
var index = 0;
function incrementIndex() {
document.getElementById("demo").innerHTML = ""+index+"";
if ($("#Xch").attr("checked") == true){
index = 10;
}
else {
index += 1;
}
}
You need to use a checkbox instead of a radiobox.
In a radio group, once an input is selected, one input in the group must always remain selected.
In a checkbox group, any number if inputs can be selected or deselected.
Change your HTML to:
<input type="checkbox" name="Xch" value="XCheese " onclick="incrementIndex()">XCheese<br>
And it should work.

Setting values to fields with the same name/key possible?

Ok, say I have a checkbox such as this:
<input type="checkbox" value="1" class="discount_select" name="select[101132]">
...and 3 text fields like this:
<input type="text" name="start[101132]">
<input type="text" name="end[101132]">
<input type="text" name="discount[101132]">
I am running some code right now that will update the text field values if the checkbox is checked, however I'm not sure if or how you can target the correct fields as they all have different ID's.
So I basically have this code to loop through the checked boxes, but not sure how to make updates to the correct text fields:
// Get values
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
// How can I target the correct fields/ID's here?
});
Try
// Get values
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
var num = this.name.substring(7, this.name.length - 1);
$('input[name="start[' + num + ']"]').val(start)
$('input[name="end[' + num + ']"]').val(end)
$('input[name="discount[' + num + ']"]').val(discount)
});
Change the name and ids of your fields to make it simpler
<input type="checkbox" value="1" class="discount_select" id="101132" name="select_101132">
<input type="text" name="start_101132">
<input type="text" name="end_101132">
<input type="text" name="discount_101132">
Then:
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
var select_id = this.attr("id");
$('[name=start_'+select_id+']').val(start);
$('[name=end_'+select_id+']').val(end);
$('[name=discount_'+select_id+']').val(discount);
});

Value of checkbox is [object HTMLInputElement]

I have two forms right next to each other.
This right here is Form one
<form>
<input type="radio" id="genderOne" name="genderOne" value="Mann"><label for="genderOne">Maennlich</label>
<input type="radio" id="genderTwo" name="genderOne" value="Frau"><label for="genderTwo">Weiblich</label><br><br>
<input type="checkbox" id="ageCheck" id="ageCheck" name="ageCheck"><label for="ageCheck">Bist du ueber 18?</label>
</form>
Form 2 is simply the same, with the difference that the IDs of the checkboxes are genderThree and genderFour and the name is genderTwo. The checkbox has also another name "ageCheckTwo".
Now I want, if everything is filled in correctly to open up a php.site with the parameters the user typed in.
Everything works, except for the second form, but only the gender.
This is the JavaScript-code for that part
if(document.getElementById('genderOne').checked || document.getElementById('genderTwo').checked)
{
if(document.getElementById('genderOne').checked)
{
var genderOne = $('#genderOne').val();
urlString += "&genderOne=" + genderOne;
}
if(document.getElementById('genderTwo').checked)
{
var genderTwo = $('#genderTwo').val();
urlString += "&genderOne=" + genderTwo;
}
}
if(document.getElementById('genderThree').checked || document.getElementById('genderFour').checked)
{
if(document.getElementById('genderThree').checked)
{
var genderOne = $('#genderThree').val();
urlString += "&genderTwo=" + genderThree;
}
if(document.getElementById('genderFour').checked)
{
var genderTwo = $('#genderFour').val();
urlString += "&genderTwo=" + genderFour;
}
}
And just to be sure, this is the second form
<form>
<input type="radio" id="genderThree" name="genderTwo" value="Mann"><label for="genderThree">Maennlich</label>
<input type="radio" id="genderFour" name="genderTwo" value="Frau"><label for="genderFour">Weiblich</label><br><br>
<input type="checkbox" id="ageCheckTwo" id="ageCheckTwo" name="ageCheckTwo"><label for="ageCheckTwo">Ist er/sie ueber 18?</label>
</form>
But, the URL is now, when I checked all parameters like this:
http://localhost/mojoGerman/questions.php?nameOne=fdgh&nameTwo=hj&genderOne=Mann&genderTwo=[object HTMLInputElement]
While it should display the gender of the second person at the end. What am I doing wrong?
Simple typographic errors here:
if(document.getElementById('genderThree').checked)
{
var genderThree = $('#genderThree').val();
urlString += "&genderThree=" + genderThree;
}
if(document.getElementById('genderFour').checked)
{
var genderFour = $('#genderFour').val();
urlString += "&genderFour=" + genderFour;
}
This is why cutting and pasting is a bad idea. Make yourself a simple function:
function addIfChecked(name) {
var val = $('#' + name).val();
return val ? "&" + name + "=" + encodeURIComponent(val) : '';
}
urlString += addIfChecked("genderOne") +
addIfChecked("genderTwo") +
addIfChecked("genderThree") +
addIfChecked("genderFour");
or something like that. Better yet, give the checkboxes a class so that you can find them with a selector and iterate over them via jQuery.
var genderOne = $('#genderThree').val(); // get value in genderThree here
urlString += "&genderTwo=" + genderThree;
Try this -
if(document.getElementById('genderThree').checked) {
var genderThree = $('#genderThree').val();
urlString += "&genderTwo=" + genderThree;
}
if(document.getElementById('genderFour').checked) {
var genderFour = $('#genderFour').val();
urlString += "&genderTwo=" + genderFour;
}
The issue is using the wrong variable names for genderThree and genderFour
But you could simplify the whole thing to
$('input[type="radio"][name^="gender"]:checked').each(function(){
urlString += '&' + this.name + '=' + this.value;
});
I have not understood completely what are you trying to do , but seeing at your code, I think It can be optimised by using different practice
<form>
<input type="radio" id="genderOne" name="genderOne[]" value="Mann"><label for="genderOne">Maennlich</label>
<input type="radio" id="genderTwo" name="genderOne[]" value="Frau"><label for="genderTwo">Weiblich</label><br><br>
<input type="checkbox" id="ageCheck" id="ageCheck" name="ageCheck"><label for="ageCheck">Bist du ueber 18?</label>
</form>
If you want to have same key on your query string genderOne , you can explicity declare your name as array in the name attribute. On your php script you can get this value using GET method to obtain those values
//php
echo $_GET['genderOne'][0];//returns first checked gender value
echo $_GET['genderOne'][1];//returns 2nd checked gender value
You don't even need the javascript for this if I understood what you are trying to achieve.

dynamic arrays with input javascript

I am currently doing a school project where I have to use javascript to create a page where a user can key in multiple numbers from an input box.
After each number is entered there is a add button which then shows the number in another box below the input. So each number is displayed vertically down the page.
From there I need two more buttons. The first one to calculate which will add the numbers together and work out the average. The second one will clear the array to start again.
I believe I am ok with the last two buttons. What I am unsure of is how should the user input create the dynamic array which will then be displayed in the page. I have been able to get a single number input but I am missing the next step so the next number entered will dispay and allow me to build an array from which the calculations can be performed.
Please try this I think it will work for you
JAVA SCRIPT :
<script type="text/javascript">
var arr = new Array();
function addNum()
{
var temp = document.getElementById('a').value;
arr.push(temp);
document.getElementById('a').value = "";
getAvg();
}
function getAvg()
{
var sum = 0;
for(var i = 0; i < arr.length; i++){
sum += parseInt(arr[i]);
}
var avg = sum/arr.length;
document.getElementById('sum').value = sum;
document.getElementById('avg').value = avg;
}
function clearAll()
{
arr.length = 0;
document.getElementById('a').value = "";
document.getElementById('sum').value = "";
document.getElementById('avg').value = "";
}
</script>
HTML:
<table>
<tr><td><input type="text" id="a"></td>
<td>Sum :<input type="text" id="sum"></td>
<td>Avg :<input type="text" id="avg"></td></tr>
<tr><td><input type="button" value="add" onclick="addNum()"></td>
<td><input type="reset" value="reset" onclick="clearAll()"></td></tr>
</table
Easiest way would be to loop over the inputs showing the numbers and add each number that way, rather than trying to maintain an array that is updated from the first input.
Stick the displaying input elements into a container with an id, then you can do something simple like:
var container = document.getElementById("container-id"),
inputs = container.children,
total;
for (var x = 0, y = inputs.length; x < y; x++) {
total += parseInt(inputs[x].value, 10);
}
alert(total) //do something way better than alert!

Categories