I am attempting to build a string of a user's "interests" that they indicate by checking off radio boxes. When I return the result, there is always an "undefined" prepended to the string of interests. I know that I can get rid of this issue by initializing var interest as an empty string, like so:
var interests ="";
But am unsure if this is the proper way to solve the issue. is there a more optimal data structure for this?
var controlIndex;
var element;
var interests;
var numberOfControls = document.form1.length;
for (controlIndex = 0; controlIndex < numberOfControls; controlIndex++)
{
element = document.form1[controlIndex];
if (element.type == "radio")
{
if (element.checked == true)
{
interests += document.form1[controlIndex].value+"\n";
console.log(interests);
document.getElementById("interests").innerHTML= interests
}
}
}
}
}
<form action="" name="form1">
<h1>Personal Details</h1>
Please enter the following details:
<br>
<p>
First Name:
<br />
<input type="text" name="txtName" onchange="txtName_onchange()"/>
</p>
<p>
Age:
<br />
<input type="text" name="txtAge" size="3" maxlength="3" onchange="textAge_onblur()" />
</p>
<p>
My interest is:
<p>Sports
<input type="radio" name="sports" value="sports"/>
</p>
<p>Politics
<input type="radio" name="politics" value="politics" />
</p>
<p>Magazines
<input type="radio" name="magazines" value="magazines">
</p>
<p>
<input type="button" value="Submit Registration" name="btnCheckForm" onclick="btnCheckForm_onclick()" >
<input type = "button" value = "Clear Details" name="btnClear" onclick="btnClear_onclick()">
</p>
</form>
</div>
I would turn your "interests" variable into an array.
var interests = [];
then I would just push into it, like so. When you want to print it out, just join it.
interests.push(document.form1[controlIndex].value);
console.log(interests.join(""));
But am unsure if this is the proper way to solve the issue ...
Yes, initialising the variable as a string is the proper way to resolve this issue.
Basically, whenever you initialise your variable like this:
var interests;
The variable type is implicitly set to undefined, so when you apply += onto it, JavaScript changes the type to string with a value of "undefined". Setting the initial value prevents that:
var interests = '';
I have tried to put same thing mentioned in above answers in code snippet for better understanding. In my opinion array suits here
function btnCheckForm_onclick (){
var controlIndex;
var element;
//Case with '' intitlization
var interests = '';
//Case with [] intitlization
var interests = [];
var numberOfControls = document.form1.length;
for (controlIndex = 1; controlIndex < numberOfControls; controlIndex++)
{
element = document.form1[controlIndex];
if (element.type == "radio")
{
if (element.checked == true)
{
// Case with []
//interests.push(document.form1[controlIndex].value);
//console.log(interests.join(" "));
//Case with ''
interests += document.form1[controlIndex].value+"\n";
console.log(interests);
}
}
}
document.getElementById("interests").innerHTML= interests
}
<form action="" name="form1">
<h1>Personal Details</h1>
Please enter the following details:
<br>
<p>
First Name:
<br />
<input type="text" name="txtName" onchange="txtName_onchange()"/>
</p>
<p>
Age:
<br />
<input type="text" name="txtAge" size="3" maxlength="3" onchange="textAge_onblur()" />
</p>
<p>
My interest is:
<p>Sports
<input type="radio" name="sports" value="sports"/>
</p>
<p>Politics
<input type="radio" name="politics" value="politics" />
</p>
<p>Magazines
<input type="radio" name="magazines" value="magazines">
</p>
<p>
<input type="button" value="Submit Registration" name="btnCheckForm" onclick="btnCheckForm_onclick()" >
<input type = "button" value = "Clear Details" name="btnClear" onclick="btnClear_onclick()">
</p>
<div id="interests"></div>
Related
I need to add a message box and e-mail textbox and display everything in my form in the 'msgresults' tag.
I need to add a Message box and and e-mail text box. Then I need all information to be shown within the MsgResults tag. The radioboxes already are shown this way.
function validateForm(){
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
if (name == "" || name == null){
resultsMsg("We need your name please");
}else{
if(age == "" || name == null || isNaN(age)){
resultsMsg("Please enter a number for your age");
}else{
if(!getSkill()){
resultsMsg("Please select the type of problem you are having.");
}else{
resultsMsg("Type of Problem: " + getSkill());
}//end else
}// end function
}
}
function getSkill(){
var isChecked = false;
var theSelection;
var skills = document.getElementsByName('skillset');
for (var i=0; i < skills.length; i++){
if(skills[i].checked){
isChecked = true;
theSelection = skills[i].value;
break;
}
}
if(isChecked){
return theSelection;
}else{
return false;
} // end else
} // end function
function resultsMsg(s){
var resultsBox = document.getElementById("results");
resultsBox.innerHTML=s;
} // end function
<form name="form1" id="form1" action="" method="post">
<label>Full Name:
<input type="text" id="name" name="name">
</label>
<br> <!-- new line here -->
<label>Your Age:
<input type="text" id="age" name="age">
</label>
<br> <!-- new line here -->
<input type="radio" name="skillset" value="Technical Issues">Technical Issues</br>
<input type="radio" name="skillset" value="Recovery Issues">Recovery Issues</br>
<input type="radio" name="skillset" value="Hardware Issues">Hardware Issues</br>
<input type="radio" name="skillset" value="Software Issues">Software Issues</br>
<input type="radio" name="skillset" value="Software Crashes">Software Crashes</br>
<input type="radio" name="skillset" value="Hardware Malfunctions">Hardware Malfunctions</br>
<input type="radio" name="skillset" value="General Problems">General Problems</br>
<input type="button" value="Submit" onClick="validateForm();"> <input type="reset" value="Clear Form">
</form>
<div id="results"></div>
If I understand your goal correctly, you want to add the given name and age to the result-div, on top of the 'Type of Problem' that is already show. That can be easily achieved by adding the correct variables to the last else-loop in your validateForm function. Something among the following should probably work:
resultsMsg("Name: "+name+ "<br>Age: " +age+ "<br>Type of Problem: " + getSkill());
This is a simple code and I don't know where I went wrong.. Name validation works if no name is entered, but it doesn't show the result when a valid name is entered.
Here's my code:
I'm just new in html and javascript, hoping i'd get help from here. Thank you
function checkname(form) {
var eobj = document.getElementById('MITname');
var jname = form.Name.value;
var error = false;
eobj.innerHTML = '';
if (jname == '') {
error = "Name is required!";
var error2 = error.fontcolor("red");
}
if (error) {
if (hasFocus == false) {
form.Name.focus();
hasFocus = true;
}
eobj.innerHTML = error2;
return false;
}
return true;
}
function showinput() {
document.getElementById('namedisplay').innerHTML = document.getElementById('MITname').value;
}
function validate() {
hasFocus = false;
var form = document.forms['form'];
var ary = [checkname];
var rtn = true;
var z0 = 0;
for (var z0 = 0; z0 < ary.length; z0++) {
if (!ary[z0](form)) {
rtn = false;
}
}
return rtn;
}
<form action="" name="form" onsubmit="return validate()">
<tr>
<td align="right">Name:<font color="red">*</font>
</td>
<td>
<input type="text" name="Name" /> <span id="MITname"> </span>
</td>
</tr>
<br/>
<input type="submit" value="Submit" onclick="showinput()" />
<br/>
<label>Your input:</label>
<p><span id="namedisplay"></span>
</p>
</form>
Few issues here. (Also, welcome to Web Development!)
First, you never actually create the variable hasFocus. So you're never actually checking if it's true/false or not.
Second, where you create error2 means that it will only be accessible within the if() block it was created in. So, in the following if(error) block when you try to access it, it will return undefined.
Third, when you create error you are setting the value to false, which indicates a Boolean type, but then later setting its value to a String, which is definitely not a Boolean.
Fourth, the line var ary = [checkname]; is confusing to me. I get that you're trying to convert the name (from the input?) to an array, but that is not the way to do it. You can access each character of the name with string.charAt(index), so creating an array isn't really necessary.
Fifth, your validate() function as a whole is very confusing. I haven't a clue what you're trying to do. It looks like your teaching source may have mislead you, or you weren't paying attention that closely.
I could go on, however those (among other) issues are really making it difficult to find exactly what is going wrong, without digging too much into it. I don't want to write this for you, and so my suggestion would be to start again, and maybe checkout some more tutorials, perhaps from a different source. (Different youtube channel, etc.)
My problem is the validation. If I enter a blank name, an error message should appear next to the Name's text box indicating to enter a valid name.
<!DOCTYPE html>
<html>
<head>
<title>JAVASCRIPT FORM VALIDATION</title>
<script type="text/JavaScript">
function showMessage()
{
var Name = document.getElementById("Name").value;
displayname.innerHTML= Name;
var Email = document.getElementById("Email").value;
displayemail.innerHTML= Email;
var Website = document.getElementById("Website").value;
displaywebsite.innerHTML= Website;
var Comment = document.getElementById("Comment").value;
displaycomment.innerHTML= Comment;
var nameerror='';
var emailerror='';
var websiteerror='';
var commenterror='';
if (displayname.innerHTML=='')
{
nameerror = 'Please enter a valid name';
return false;
}
return true;
}
</script>
</head>
<body>
Name: <input type="text" id = "Name"> <span id = "nameerror"> </span>
<br></br>
Email: <input type="text" id = "Email">
<br></br>
Website: <input type="text" id = "Website">
<br></br>
Comnent: <textarea cols="35" rows="7" id="Comment"> </textarea>
<br></br>
<input type="submit" onclick="showMessage()" value="submit" />
<p>Name: <span id = "displayname"></span> </p>
<p>Email: <span id = "displayemail"></span> </p>
<p>Website: <span id = "displaywebsite"></span> </p>
<p>Comment: <span id = "displaycomment"></span> </p>
</body>
</html>
<form action="" name="form" onsubmit="return validate()">
<tr>
<td align="right">Name:<font color="red">*</font>
</td>
<td>
<input type="text" name="Name" /> <span id="MITname"> </span>
</td>
</tr>
<br/>
<input type="button" value="Submit" onclick="showinput()" />
<br/>
<label>Your input:</label>
<p><span id="namedisplay"></span>
</p>
</form>
Just remove type='submit' in your code it will submit your page while click once you click submit the data's are change to POST , So use button as type
I want to use billingname[] and billingcity[] instead but I don't know how to write .value for these input. (Now I use ordinal number such as billingname1, billingname2 but I don't want ordinal number)
<script>
function FillBilling(f) {
if(f.billingtoo1.checked == true) {
f.billingname1.value = f.shippingname.value;
f.billingcity1.value = f.shippingcity.value;
}
if(f.billingtoo1.checked == false) {
f.billingname1.value = '';
f.billingcity1.value = '';
}
if(f.billingtoo2.checked == true) {
f.billingname2.value = f.shippingname.value;
f.billingcity2.value = f.shippingcity.value;
}
if(f.billingtoo2.checked == false) {
f.billingname2.value = '';
f.billingcity2.value = '';
}
}
</script>
<td bgcolor="eeeeee">
<b>Mailing Address</b>
<br><br>
<form id="add_field">
Name:
<input type="text" name="shippingname">
<br>
City:
<input type="text" name="shippingcity">
<br>
<input type="checkbox" onclick="FillBilling(this.form)" name="billingtoo1">
<em>Check this box if Billing Address and Mailing Address are the same.</em>
<p>
<b>Billing Address</b>
<br><br>
Name:
<input type="text" name="billingname1">
<br>
City:
<input type="text" name="billingcity1">
</p>
<input type="checkbox" onclick="FillBilling(this.form)" name="billingtoo2">
<em>Check this box if Billing Address and Mailing Address are the same.</em>
<p>
<b>Billing Address</b>
<br><br>
Name:
<input type="text" name="billingname2">
<br>
City:
<input type="text" name="billingcity2">
</p>
</form>
</td>
If you're not going to give each field a unique identificator (maybe a id property), you have to iterate over all of them in order to get the value for each one:
$('input[name="billingname[]"]').each(function() {
this.value = f.shippingname.value;
});
Not sure how the code actually works on your environment, but it should give you an idea.
So i have a dynamic input field came from append with different class name and names, i want to check each of input field value already exist or duplicate.
This would look like
The first criteria_name is default and the others are appendend.
<input type="text" name="criteria_name" class="criteria_name">
<input type="text" name="criteria_name2" class="criteria_name2">
<input type="text" name="criteria_name3" class="criteria_name3">
<input type="text" name="criteria_name4" class="criteria_name4">
<input type="text" name="criteria_name5" class="criteria_name5">
I am trying to check each one of those if there is no duplicated else proceed.
var critname_arr = [];
var input_check;
var crit_name_of_first = $('input.criteriaNames').val();
var acappended = append_crit_header+1;
var count_to = 0;
for(var ab = 2; ab<=acappended; ab++){
var crit_arr;
if(crit_name_of_first == $('input.criteria_each_name'+ab+'').val()){
alert("Criteria cannot be duplicate");
return false;
}else{
input_check = $('input.criteria_each_name'+ab);
input_check.each(function(){
crit_arr = $.trim($(this).val());
});
critname_arr.push(crit_arr);
}
if($('input.criteria_each_name'+ab+'').val() == critname_arr[count_to]){
alert('criteria cannot be duplicate');
return false;
}
count_to++;
}
console.log(critname_arr);
Here is just an example of how you can do it. In the fiddle change one of the values to one that is already in another field (make a duplicate value) to see it do something. If there are no duplicates, it will not do anything. Click the "Button" text to run the duplicate check:
jsFiddle: https://jsfiddle.net/o52gjj0u/
<script>
$(document).ready(function(){
$('.ter').click(function(e) {
var stored = [];
var inputs = $('.criteria_name');
$.each(inputs,function(k,v){
var getVal = $(v).val();
if(stored.indexOf(getVal) != -1)
$(v).fadeOut();
else
stored.push($(v).val());
});
});
});
</script>
<!-- Just use an array name for the input name and same class name as well -->
<div class="ter">Button</div>
<input type="text" name="criteria_name[]" class="criteria_name" value="1" />
<input type="text" name="criteria_name[]" class="criteria_name" value="2" />
<input type="text" name="criteria_name[]" class="criteria_name" value="3" />
<input type="text" name="criteria_name[]" class="criteria_name" value="4" />
<input type="text" name="criteria_name[]" class="criteria_name" value="5" />
I have this function here:
function nameSplit() {
var option_result = document.getElementById("fname").value;
var option_array=option_result.split(" ");
document.getElementById('first_name').value = option_array[0];
document.getElementById('last_name').value = option_array[1];
}
function myFunction() {
var option_result = document.getElementById("fname").value;
document.getElementById("demo").innerHTML = option_result.length;
document.getElementById("demo2").innerHTML = option_array.prototype.length;
}
<form>
<label>Name:</label>
<input type="text" id="fname">
<input type='button' onclick='nameSplit()' value='Change Text'/>
</form>
<br>
<input id="first_name" name="fid" value="" />
<input id="last_name" name="sid" value="" />
<br>
option_result: <p id="demo"></p>
option_array: <p id="demo2"></p>
<button onclick="myFunction()">Try it</button>
As you can see my option_array.prototype.length; is not returning anything. So I don't know the best way the explain this but in short I want to determine how many arrays are within the function and have that as the number that is being pulled at
document.getElementById('last_name').value = option_array[1];
I want it to work like this:
document.getElementById('last_name').value = option_array[(Number of total arrays)];
If you run the original function and type "John Doe" it will split it into "John" and "Doe", but if you change the input to "John Doe Jr." it will still return with "John" and "Doe". I want it to return "John" and "Doe Jr."
I have tried to create a script that runs option_array[1] + " " + option_array[2]; but if a person only uses two parts of the array, the third comes back undefined.
Any ideas?
Well I thought this function would be a great way to retrieve the information I needed but my boss stop by my desk and told me there was an easier way, and gave me some information to do research on, and so I went on to build a new one..
Here is the code for anyone interested:
function nameSplit() {
var first_name = document.getElementById("first_name");
var last_name = document.getElementById("last_name");
var fname = document.getElementById("fname");
var myfname = fname.value.trim();
if (myfname.indexOf(" ") < 0)
{
first_name.value = fname.value.trim();
last_name.value = "Undefined";
} else {
first_name.value = fname.value.substring(0, fname.value.indexOf(" "));
last_name.value = fname.value.substring((fname.value.indexOf(" ") + 1), fname.value.length);
}
}
<form>
<label>Name:</label>
<input type="text" id="fname">
<input type='button' onclick='nameSplit()' value='Submit'/>
</form>
<br>
<input id="first_name" value="" />
<input id="last_name" value="" />
Thanks for your help #jongware