Value of checkbox is [object HTMLInputElement] - javascript

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.

Related

Don't append if string already contains OnChange

I have a javascript OnChange function on a column having textboxes which captures the name of each row in a column. I am appending all the names and storing in variable.
Now , suppose user clicks same textbox again , I don't want to append that name again.
var AppendedString = null;
function onChangeTest(textbox) {
AppendedString = AppendedString;
AppendedString = AppendedString + ';' + textbox.name;
// this gives null;txt_2_4;txt_2_6;txt_3_4;txt_2_4 and so on..and I don't want to append same name again , here it's txt_2_4
}
My Input text :
<input type="text" name="txt_<%=l_profileid %>_<%=l_processstepsequence%>" value="<%= l_comments%>" onfocus="this.oldvalue = this.value;" onchange="onChangeTest(this);this.oldvalue = this.value;">
Those rows seem to have unique names.
you can simply check if AppendedString already contains that name :
var AppendedString=''
function onChangeTest(textbox) {
if (!AppendedString.includes(textbox.name)) {
AppendedString += ';' + textbox.name;
}
}
Codepen Link
You can’t initialize AppendedString as null otherwise, the includes() method won’t be available
otherwise, you can give each row a unique ID, and store in an array IDs that already have been clicked by the user.
var AppendedString = '';
var clickedRows = [];
function onChangeTest(textbox) {
if (!clickedRows.includes(textbox.id)) {
AppendedString += ';' + textbox.name;
clickedRows.push(textbox.id)
}
}
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!(arr.indexOf(nowS) > -1)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
Somewhat similar to your need,
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!arr.includes(nowS)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
You can add flag your textboxes and ignore if it's clicked again. Like using jquery you can do something like this:
function onChangeTest(textbox) {
AppendedString = AppendedString;
if (!textbox.hasClass("clicked")){
AppendedString = AppendedString + ';' + textbox.name;
textbox.AddClass("clicked");
}
}

How do I change the value of an input text field based on if a checkbox is checked or not?

Basically I have an email field, then a checkbox under it. If it's checked i want it to change the value of the email address field to something like originalemailATgmail.com#mydomain.com then if it's unchecked I want it to display "originalemail#gmail.com" that it started with. I'm having a problem switching back to the original email value after changing it to "derrrr"
[html]
<input type="email" name="email_address" value="originalemail#gmail.com" id="email_addressez">
<input type="checkbox" name="post_date_email" value="post_date_email" id="post_date_email" onclick="postDateEmail(document.getElementById("email_addressez").value)">
function postDateEmail(email){
var emailchecked=document.getElementById("post_date_email").checked;
var emailsub = "derrrrrr";
var originalemail = email;
alert("email is "+email+" checked is "+emailchecked);
if(emailchecked=true){
//var email=document.getElementById("email_addressez").value;
alert("in if, email is " + email + " checked is "+emailchecked);
document.getElementById("email_addressez").value = emailsub;
}else{
alert("else" + email + " checked is "+emailchecked);
document.getElementById("email_addressez").value = email;
}
}
[/html]
This is a working sample of what you are trying to do.
And notably, when writing conditional operation like if else statements.
You use == or === depending on what you want.
In your case, using = is an assignment operator so your if statement will not work at all.
Below is a simplified version using ternary operators ? and :
function postDateEmail() {
var checked = document.getElementById('post_date_email').checked;
document.getElementById('email_addressez').value = 'originalemail' + (checked ? 'AT' : '') + '#gmail.com';
}
<input type="email" name="email_address" value="originalemail#gmail.com" id="email_addressez">
<input type="checkbox" name="post_date_email" value="post_date_email" id="post_date_email" onclick="postDateEmail()">
ended up modifying your code to this:
var checked = document.getElementById('post_date_email').checked;
var originalemail = <?php echo(json_encode($email)); ?>;
var postDateEmailAddy = originalemail.replace("#", "AT");
var postDateEmailAddy = postDateEmailAddy.replace(".com", ".com#mydomain.com");
//alert(postDateEmailAddy);
document.getElementById('email_addressez').value = (checked ? postDateEmailAddy : originalemail);
where $email is defined elsewhere in the php.

jquery how get and makes array of input classes value

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

Display number of days based on selected month (with a for loop)

I'm trying to create a form where users can select a month, and then it shows checkboxes with all the days in that month.
Now, I've got this:
<form name="form">
<div>
<label for="month">Maand:</label>
<select id="month" name="month" onChange="selMonth()">
<option value="-1" disabled selected>--Pick A Month--</option>
<option value="4" >april</option>
<option value="5" >mei</option>
<option value="6" >juni</option>
</select>
</div>
<div>
Days:<br />
<script type="text/javascript">
function daysInMonth(month,year)
{
return new Date(year, month, 0).getDate();
}
function selMonth() {
var slctdM = document.form.month.value;
var dys = daysInMonth(slctdM,2014);
for(i = 1; i <= dys ; i++)
{
document.write('<span style="width:10%;display:inline-block;"><input type="checkbox" id="' + i + '" /><label for="day_' + i + '">Dag ' + i + '</label></span>');
}
}
</script>
</div>
</form>
I get the correct values, and the correct number of boxes get displayed, but erase everything on the page (so, the rest of the page and form gets erased. Also, the page keeps loading after all the boxes are shown on screen.
There is probably a simple fix for this or a stupid mistake I made, since I'm not that familiar with javascript.
At first I wrote the for loop with php, but I decide to use javascript instead, because I want the number of boxes to update dynamically when a certain month is selected.
UPDATES
I now see that the page only keeps loading in Firefox, in Chrome the page finishes loading, but only shows the boxes.
I think the problem lies with the function selMonth(), because it is called with onChange, so when the month is changed, it only does document.write, and thinks it can forget the rest. But I don't know how to solve this. Moving the loop outside of the function doesn't solve my problem.
You might want to use .innerHTML instead of document.write().
I guess what you would like to do is something like this:
DEMO :http://jsfiddle.net/UaAX5/
HTML:
Days:<br />
<div id="days_area"></div>
JavaScript:
function selMonth() {
var slctdM = document.form.month.value;
var dys = daysInMonth(slctdM,2014);
var boxes = "";
for(i = 1; i <= dys ; i++)
{
boxes += '<span style="width:10%;display:inline-block;">'+
'<input type="checkbox" id="' + i + '" />'+
'<label for="day_' + i + '">Dag ' + i + '</label></span>';
}
document.getElementById('days_area').innerHTML = boxes;
}
The document of innerHTML is here :
https://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML
Hope this helps.
document.write overwrites your entire document.
What you should do instead is append to the innerHTML of your form.
function selMonth() {
var slctdM = document.form.month.value;
var dys = daysInMonth(slctdM,2014);
var frm = document.forms[0];
for(i = 1; i <= dys ; i++)
{
frm.innerHTML += '<span style="width:10%;display:inline-block;"><input type="checkbox" id="' + i + '" /><label for="day_' + i + '">Dag ' + i + '</label></span>';
}
}

jQuery or Javascript to parse querystring on submit

This form has multiple choices through a checkbox. Eg. Pet You Own is a multiple choice and there are various options such as Cat, Dog, Mule etc.
Now by default, the querystring sent will look like:
?pet=dog&pet=cat&pet=mule
given all 3 are checked.
I need a way to parse this so that the querystring looks like:
?pet=dog,cat,mule
Another requirement is that, there are other parameters/inputs in the form so it needs to work in conjunction with other standard form inputs.
The format you're currently seeing is the conventional format. If your form fields were named pet[] rather than pet, your server would be able to interpret the result as an array.
Having said that, to actually do what you're requesting, you could reset the name attribute of your checkboxes, so that they won't be posted, and instead post a hidden field that holds the value of your checkboxes as a comma separated string:
$('#my-form').submit(function() {
var pets = [];
$('input[name=pet]:checked').each(function() {
pets.push($(this).val());
});
// stop checkboxes from being posted
$('input[name=pet]').attr('name','');
// have an input field be posted instead
$('#my-hidden-field')
.val(pets.join(','))
.attr('name', 'pet');
});
A bit of cleaning is needed but using this with plain JS you can acheive
<html>
<head>
<title>My Page</title>
<script>
function myFunction(){
var options = "";
if(document.getElementById("option1").checked){
options = options+"Milk";
}
if(document.getElementById("option2").checked){
options = options+",Butter";
}
if(document.getElementById("option3").checked){
options = options+",Cheese";
window.location = "end.html&options="+options
}
}
</script>
</head>
<body>
<div align="center"><br>
<input id="option1" type="checkbox" name="option1" value="Milk"> Milk<br>
<input id="option2" type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input id="option3" type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
</div>
Button to submit
</body>
</html>
I suggest you to do this job on server side. When your server receive this request, it will get an array which is called pet and has three element: dog,cat and mule. you can conjunction them easily.
====
I implement this with JavaScript:
var str = window.location.href;
var queryString = "", temp = {};
str = str.substring(str.lastIndexOf("?") + 1);
str.split("&").some(function(item) {
var tarr = item.split("=");
if(typeof temp[tarr[0]] == "undefined") {
temp[tarr[0]] = tarr[1];
} else if(typeof temp[tarr[0]] == "string") {
temp[tarr[0]] += "," + tarr[1];
}
});
// Make queryString
for(var i in temp) {
queryString += "&" + i + "=" + temp[i];
}
queryString = queryString.replace(/^./,"");
//
var href = window.location.href;
console.log("before:", href);
href = href.replace(/\?.*$/, "?");
// the url is that you want
console.log("after:", href + queryString);
//window.location.href = href + queryString;
OUTPUT:
before:
http://www.boutell.com/newfaq/creating/forcedownload.html?pet=dog&pet=cat&pet=mule&animal=camel
after:
http://www.boutell.com/newfaq/creating/forcedownload.html?pet=dog,cat,mule&animal=camel
Name your check boxes as p1, p2 etc. Have a hidden field in your form named 'pet'. Just before submit using JS, set the value of your hidden variable the way you need and return true.
function beforeSubmit() {
var p = '';
if($('#p1').attr('checked')==true) p += ',cat';
if($('#p2').attr('checked')==true) p += ',dog';
...
p = p.substring(1); // strip the , at 0
$('#pet').val(p);
return true;
}
and your form should be like:
<form ... onsubmit="return beforeSubmit()">
...
<input type="checkbox" name="p1" id="p1">Cat<br>
<input type="checkbox" name="p2" id="p2">Dog<br>
...
<input type="hidden" name="pet" id="pet" value="">
</form>

Categories