Javascript radio button not copying fields when clicked - javascript

I have a script that is supposed to copy once set of form fields to another when a radio button is checked. It works on Safari, firefox (mac) but not on FF (PC) or IE.
function checkFirstDirAddrs() {
var i;
//checking which radio button selected
for ( i = 0; i < FirstCorpDirAddOption.length; i++) {
if (FirstCorpDirAddOption[i].checked == true) {
switch(i)
{
case 0:
document.getElementById("First_Corp_Director_Address1").value = document.getElementById("Corp_Address1").value;
document.getElementById("First_Corp_Director_Address2").value = document.getElementById("Corp_Address2").value;
document.getElementById("First_Corp_Director_City").value = document.getElementById("Corp_City").value;
document.getElementById("First_Corp_Director_Postal").value = document.getElementById("Corp_Postal").value;
break
case 1:
document.getElementById("First_Corp_Director_Address1").value = '';
document.getElementById("First_Corp_Director_Address2").value = '';
document.getElementById("First_Corp_Director_City").value = '';
document.getElementById("First_Corp_Director_Postal").value = '';
break
}
}
}
}
The html....
<div class="form-group">
<div class="col-sm-10"><strong>*Director Address</strong></div>
<div class="col-sm-6">
<div class="radio">
<label>
<input name="FirstCorpDirAddOption" id="FirstCorpDirAddOption" type="radio" value="Same as Corporate Address" onClick="checkFirstDirAddrs();">
Same as Corporate Address<br>
</label>
<label>
<input name="FirstCorpDirAddOption" id="FirstCorpDirAddOption" type="radio" value="Other" onClick="checkFirstDirAddrs();">
Other <em>(provided below)</em>
</label>
</div>
</div>
</div>
<div class="form-group">
<label for="First_Corp_Director_Address1" class="col-sm-2 control-label">*Address:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="First_Corp_Director_Address1" name="First_Corp_Director_Address1" maxlength="80">
</div>
</div>
<div class="form-group">
<label for="First_Corp_Director_Address2" class="col-sm-2 control-label">Address 2:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="First_Corp_Director_Address2" name="First_Corp_Director_Address2" maxlength="80">
</div>
</div>
<div class="form-group">
<label for="First_Corp_Director_City" class="col-sm-2 control-label">*City:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="First_Corp_Director_City" name="First_Corp_Director_City" maxlength="50">
</div>
</div>
<div class="form-group">
<label for="First_Corp_Director_Postal" class="col-sm-2 control-label">*Postal/Zip:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="First_Corp_Director_Postal" id="First_Corp_Director_Postal" maxlength="7">
<span class="help-block">(enter NA if not from Canada/USA)</span>
</div>
</div>
If anyone can shed some more light on the issue that would be great. It works fine on most Mac based browsers I tested on and throws no errors in the Console of dev tools.

As I know there is no standard for treating same ids in one document via global variable.
It's good to know about reference between ids and global variable they initialize. But God please, do not use it. You can use any selector or create different ids instead of trying to get ids with 'FirstCorpDirAddOption'. Just like this, for example:
document.querySelectorAll('.radio input')
Just check what you get via global variable:
Here is Chrome
Here is FF
They are different. Thus you can't use same code for them.

You need to get rid of the duplicate IDs as they are causing you trouble.
You have 3 options if you get rid of the duplicate IDs to still have a 'hook' that JavaScript can use to access the elements.
Option 1: access the elements by name
Option 2: access the elements by a new CSS class name
Option 3: access the elements by some other "loosely defined" method
For simplicity I'm going to recommend #1, but #2 is just as good.
<div class="radio">
<label>
<input type="radio" name="FirstCorpDirAddOption" value="Same as Corporate Address" onclick="checkFirstDirAddrs();"/>
Same as Corporate Address
</label>
<br/>
<label>
<input type="radio" name="FirstCorpDirAddOption" value="Other" onclick="checkFirstDirAddrs();"/>
Other <em>(provided below)</em>
</label>
</div>
Now the JavaScript to access the input(s):
function checkFirstDirAddrs(){
var i;
//checking which radio button selected
var firstCorpDirOptions = document.querySelectorAll('input[name="FirstCorpDirAddOption"]');
for(i=0;i<firstCorpDirOptions.length;i++){
if(firstCorpDirOptions[i].checked == true){
//...

Related

how to make these two components appear on the same line? (textbox label and the textbox)

this is my html file
<div id="radioHeader">
<div id="radioHeader" onclick="radioClicked()">
<div class="radio form-check form-check-inline component"> Mode of Transaction<span
style="color:red;">*</span>
<div class="radiogq">
<input type="radio" name="mode" value="cheque" onclick="" checked> Cheque
<input type="radio" name="mode" value="bank"> Bank Transaction
</div>
</div>
<div>
<p id="idc"></p><input class="textb" type="text" id="fname" class="col-form-label input" placeholder="Registration Id"
name="fname" size="100">
</div>
</div>
</div>
this is my js file from where I am adding the value in the textbox, and I want them to be in the same line.
this textbox label will chance as per the change in the radio button
function radioClicked() {
let shapeChoice = document.querySelector('input[name="mode"]:checked').value;
switch (shapeChoice) {
case 'cheque':
document.getElementById("idc").innerHTML = "Enter your Cheque Id"
break;
case 'bank':
document.getElementById("idc").innerHTML = "Enter your Transaction Id"
break;
default:
doucment.getElementById("idc").innerHTML = "Default"
}
};
radioClicked();
Use CSS, one of the ways is float:left
function radioClicked() {
let shapeChoice = document.querySelector('input[name="mode"]:checked').value;
switch (shapeChoice) {
case 'cheque':
document.getElementById("idc").innerHTML = "Enter your Cheque Id"
break;
case 'bank':
document.getElementById("idc").innerHTML = "Enter your Transaction Id"
break;
default:
doucment.getElementById("idc").innerHTML = "Default"
}
};
radioClicked();
.cs1 {
float:left;
}
<div id="radioHeader">
<div class="radio form-check form-check-inline component" "> Mode of Transaction<span
style="color:red;">*</span></div>
<div id="radioHeader" onclick="radioClicked()">
<div class="cs1 radiogq">
<input type="radio" name="mode" value="cheque" onclick="" checked> Cheque
<input type="radio" name="mode" value="bank"> Bank Transaction
</div>
</div>
<div class='cs1'> </div>
<div class='cs1' style="position:relative;top:2px;" id=idc></div>
<div class='cs1'> </div>
<div class='cs1'>
<input class="textb" type="text" id="fname" class="col-form-label input" placeholder="Registration Id"
name="fname" style="width:200px;max-width:100%:">
</div>
</div>
I've added a few improvements to your script and made sure your idc element floats left. This makes sure that the next element will appear next to it. To make it look better, I also added some margins to the input box.
Keep in mind that it may look like it doesn't work properly here on Stack Overflow as the window for the example is pretty small. But it'll work fine in your browser.
// Make sure it runs after the page is loaded
document.addEventListener("DOMContentLoaded", function(e){
// Get all radio buttons where name equals "mode"
const radios = document.querySelectorAll('input[type=radio][name="mode"]');
function radioChangeHandler(event){
const idc = document.getElementById("idc");
if(this.value === "cheque"){
idc.innerText = "Enter your Cheque Id";
} else if(this.value === "bank"){
idc.innerText = "Enter your Transaction Id";
} else {
idc.innerText = "Default";
}
}
// Attach event handler to each radio button
Array.prototype.forEach.call(radios, function(radio) {
radio.addEventListener('change', radioChangeHandler);
});
});
#idc {
float: left;
}
#fname {
margin-top: 13px;
margin-left: 5px;
}
<div id="radioHeader">
<div id="radioHeader">
<div class="radio form-check form-check-inline component"> Mode of Transaction<span style="color:red;">*</span>
<div class="radiogq">
<input type="radio" name="mode" value="cheque" onclick="" checked> Cheque
<input type="radio" name="mode" value="bank"> Bank Transaction
</div>
</div>
<div>
<p id="idc"></p><input class="textb" type="text" id="fname" class="col-form-label input" placeholder="Registration Id" name="fname" size="100">
</div>
</div>
</div>
Reference for the radio event handler: How to use radio on change event?
The behavior is because the paragraph i.e. element by default is block element. So, it occupies a block and adds line break before and after it. So, one way of changing it would be to change the behavior of paragraph block i.e. element by changing the display property to inline or inline block. Since it already has any id of idc, it can be done as :-
#idc {
display: inline;
}
Alternatively, the label and input can be placed inside the paragraph and it will display in the same line given there is enough to accommodate the element. This is the better approach since, a label tag is used for displaying the label and is linked to the input with for attribute.
<p>
<label id="idc" for="fname"></label>
<input class="textb" type="text" id="fname" class="col-form-label input" placeholder="Registration Id" name="fname" size="100">
</p>

Show div when radio button is checked, and hide all the other divs?

I'm very new here, any help would be appreciated.
I’m trying to make a contact form which has 5 radio buttons, each radio button has its own div. Inside the div there's a textarea. When radio button 1 is checked, it shows the div, when radio button 2 is checked, it shows the div, but hides the div checked in radio button 1.
Checked radio buttons don't have to be in sequence, they just have to hide the other divs and show the div that is controlled in the currently radio button selected.
I’ve got it as far as when the radio button is checked it shows the div, but it does not hide the div when you select another radio button (all the divs remain shown when you check the radio buttons).
Below the code:
function radioCheck(radio) {
data = radio.getAttribute("data")
switch (data) {
case '1':
document.getElementById('ifRadio'+data).style.display = 'block';
break;
case '2':
document.getElementById('ifRadio'+data).style.display = 'block';
break;
case '3':
document.getElementById('ifRadio'+data).style.display = 'block';
break;
case '4':
document.getElementById('ifRadio'+data).style.display = 'block';
break;
case '5':
document.getElementById('ifRadio'+data).style.display = 'block';
break;
default:
document.getElementById('ifRadio1').style.display = 'none';
}
}
<!--Radio buttons-->
<div class="col-md-6">
<label class="radio-inline">1
<input type="radio" onclick="javascript:radioCheck(this);" data=1 name="fid_7" id="showCheck1"></label>
<label class="radio-inline">2
<input type="radio" onclick="javascript:radioCheck(this);" data=2 name="fid_7" id="showCheck2"></label>
<label class="radio-inline">3
<input type="radio" onclick="javascript:radioCheck(this);" data=3 name="fid_7" id="showCheck3"></label>
<label class="radio-inline">4
<input type="radio" onclick="javascript:radioCheck(this);" data=4 name="fid_7" id="showCheck4"></label>
<label class="radio-inline">5
<input type="radio" onclick="javascript:radioCheck(this);" data=5 name="fid_7" id="showCheck5"></label>
</div>
<!--If radio 1-->
<div id="ifRadio1" style="display:none">
Why did you rate us that way? <br><textarea type="text" id='Radio1' name='yes'></textarea><br>
What’s not working well?<br> <textarea class="form-control" type="text"></textarea>
</div>
<!--If radio 2-->
<div id="ifRadio2" style="display:none">
Why did you rate us that way? <br><textarea class="form-control" type="text" id='Radio2' name='yes'></textarea><br>
What’s not working well?<br> <textarea class="form-control" type="text"></textarea>
</div>
<!--If radio 3-->
<div id="ifRadio3" style="display:none">
Why did you rate us that way? <br><textarea class="form-control" type="text" id='Radio3' name='yes'></textarea><br>
How better can we suit your needs? <br><textarea class="form-control" type="text"></textarea>
</div>
<!--If radio 4-->
<div id="ifRadio4" style="display:none">
Why did you rate us that way? <br><textarea class="form-control" type="text" id='ifRadio4' name='yes'></textarea><br>
Do our timing works for you? <br><textarea class="form-control" type="text"></textarea>
</div>
<!--If radio 5-->
<div id="ifRadio5" style="display:none">
Why did you rate us that way? <br><textarea class="form-control" type="text" id='ifRadio4' name='yes'></textarea><br>
Do our timing works for you? <br><textarea class="form-control" type="text"></textarea>
</div>
The tips I can give you in tackling your problem are:
Styles should be in the stylesheet as it would be efficient to just add or remove classes when styling dynamically.
In your style sheet you could have this, the chosen referring to the text of the clicked radio button while the notChosen is used to hide the text of the other radio buttons
.chosen { display: initial; }
.notChosen { display: none; }
And in your javascript you could just place an event handler in the radio buttons and add/remove the .chosen or the .notChosen class.
How to add or remove classes using vanilla javascript.
To efficiently hide the rest without a very lengthy code, you can use siblings to refer to the other radio buttons and add the class notChosen to them
How to implement siblings in vanilla javascript
I suggest that you try to learn jQuery as it would solve your problem and future problems with more ease.
To add or remove classes in jQuery you just need to use toggleClass()
To refer to the other radio buttons other than the clicked one using jQuery you just need to use siblings()
Using your current coding style on this project with data attributes, events in the inline onclick fashion, and etc, so that you can see how this possible fix relates to your existing code and question closely.
First, you have to have a way to either remember which div is "open" or simply as the following demonstrates: hide them all before showing the relevant one. It happens so quick that there will be no visible difference.
function radioCheck(radio) {
data = radio.getAttribute("data")
// Hide all divs
for (var i = 0; i < 5; i++) { // assuming your data attr 1,2,3,..,N
var el = 'ifRadio' + (i + 1); // ifRadio1, ifRadio2, etc
document.getElementById(el).style.display = "none";
}
// Show the current div
var el = 'ifRadio' + (data); // ifRadio1, ifRadio2, etc
document.getElementById(el).style.display = "block";
}
<div class="col-md-6">
<label class="radio-inline">1
<input type="radio" onclick="javascript:radioCheck(this);" data=1 name="fid_7" id="showCheck1"></label>
<label class="radio-inline">2
<input type="radio" onclick="javascript:radioCheck(this);" data=2 name="fid_7" id="showCheck2"></label>
<label class="radio-inline">3
<input type="radio" onclick="javascript:radioCheck(this);" data=3 name="fid_7" id="showCheck3"></label>
<label class="radio-inline">4
<input type="radio" onclick="javascript:radioCheck(this);" data=4 name="fid_7" id="showCheck4"></label>
<label class="radio-inline">5
<input type="radio" onclick="javascript:radioCheck(this);" data=5 name="fid_7" id="showCheck5"></label>
</div>
<!--If radio 1-->
<div id="ifRadio1" style="display:none">
Why did you rate us that way? <br><textarea type="text" id='Radio1' name='yes'></textarea><br>
What’s not working well?<br> <textarea class="form-control" type="text"></textarea>
</div>
<!--If radio 2-->
<div id="ifRadio2" style="display:none">
Why did you rate us that way? <br><textarea class="form-control" type="text" id='Radio2' name='yes'></textarea><br>
What’s not working well?<br> <textarea class="form-control" type="text"></textarea>
</div>
<!--If radio 3-->
<div id="ifRadio3" style="display:none">
Why did you rate us that way? <br><textarea class="form-control" type="text" id='Radio3' name='yes'></textarea><br>
How better can we suit your needs? <br><textarea class="form-control" type="text"></textarea>
</div>
<!--If radio 4-->
<div id="ifRadio4" style="display:none">
Why did you rate us that way? <br><textarea class="form-control" type="text" id='ifRadio4' name='yes'></textarea><br>
Do our timing works for you? <br><textarea class="form-control" type="text"></textarea>
</div>
<!--If radio 5-->
<div id="ifRadio5" style="display:none">
Why did you rate us that way? <br><textarea class="form-control" type="text" id='ifRadio4' name='yes'></textarea><br>
Do our timing works for you? <br><textarea class="form-control" type="text"></textarea>
</div>
Since your data attr are all sequential (without skipping) you can use a simple loop to hide them all, see the comments in code I included there. I stored the element name to el only to enhance readability.
Stylz, I don't know if this is what you mean but the solution I found is this:
function display() {
var div0classes = document.getElementById("radio0div").classList;
var div1classes = document.getElementById("radio1div").classList;
var div2classes = document.getElementById("radio2div").classList;
if (document.getElementById('radio0').checked) {
div1classes.add("hidden");
div2classes.add("hidden");
} else if (document.getElementById('radio1').checked) {
div0classes.add("hidden");
div2classes.add("hidden");
} else if (document.getElementById('radio2').checked) {
div0classes.add("hidden");
div1classes.add("hidden");
}
}
<form>
<input type="radio" name="radio" id="radio0" value="radio0">radio0<br>
<div id="radio0div">
u can see me yay.
</div>
<input type="radio" name="radio1" id="radio1" value="radio1">radio1<br>
<div id="radio1div">
u can see me yay.
</div>
<input type="radio" name="radio2" id="radio2" value="radio2">radio2<br><br>
<div id="radio2div">
u can see me yay.
</div>
<button type="button" onclick="display()">
Submit
</button> And this is the script I used to check if a radio is checked.

Form in HTML with button assigns the value of the last button, no matter which one was selected

I want to create a form with HTML with different types of inputs (such as name, surname, dates, and radio-button options), and when I want to print the object with the data inputted in the form on the console, the value from the radio-buttons is not stored correctly.
First of all, this is my first project on this area and also my first posted question on stackoverflow, so I would appreciate some suggestions on how to pose the question better if I'm forgetting some crucial data.
I have been following help from different resources (mostly youtube videos such as: https://www.youtube.com/watch?v=GrycH6F-ksY ) to create this form and submit the data with AJAX, and the code of my javascript application comes mainly from that video.
All the data is stored correctly and I can see it in the console, except from the data comming from the radio-buttons. No matter what option is selected (either "male" or "female"), the console always shows the value of the last button, which in this case is "female". I suppose I am doing something wrong when defining these buttons, and why they are not being "selected" (I suppose that's what is happening since the data shown is always the last default value) but I haven't been able to find out where I am doing something wrong.
I'm including the part of the code that I think might be relevant
<form action="ajax/contact.php" method="post" class="ajax">
<div class="form-row">
<div class="form-group col-md-6">
<label>Name</label>
<input type="text" class="form-control" name="inputName" required>
</div>
<div class="form-group col-md-6">
<label>Surname</label>
<input type="text" class="form-control" name="inputSurname" required>
</div>
</div>
<div class="form-group">
<label>Date of birth</label>
<input type="date" class="form-control" name="inputDate">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" name="inputEmail" required>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label>Gender</label>
</div>
<div class="form-group col-md-4">
<div class="radio-inline"><input type="radio" name="inputGender"
value="male">Male</div>
</div>
<div class="form-group col-md-4">
<div class="radio-inline"><input type="radio" name="inputGender"
value="female">Female</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Number of children</label>
</div>
<div class="form-group col-md-6">
<input type="number" class="form-control" name="inputNumber">
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Javascript function
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(data);
return false;
});
PHP file
<?php
if (isset($_POST['inputName'],$_POST['inputSurname'],$_POST['inputDate'],$_POST['inputEmail'],$_POST['inputGender'],$_POST['inputNumber'])) {
print_r($_POST);
}
In the console I'm getting this:
${inputName: "myName", inputSurname: "mySurname", inputDate: "2019-12-13",
$inputEmail: "myMail#gmail.com", inputGender: "female", …}
$inputDate: "2019-12-13"
$inputEmail: "myMail#gmail.com"
$inputGender: "female"
$inputName: "myName"
$inputNumber: "1"
$inputSurname: "mySurname"
$_proto_: Object
but I thought it would be showing:
$...
$inputGender: "male"
$...
when the male option is selected.
Thank you very much
The problem is in your JS. You're looping through everything with a name attribute, in order, and adding its value to your submit data. In the case of radio buttons, you have to check if they're selected and only add if so, otherwise, the last one always wins, as you're seeing.
And since you appear to be using jQuery, you can probably just let its serialize helper do this work for you.

Change input form when checkbox is pressed

I would like to create a webform which gives users the opportunity to create tickets more easily.
In this webform I have two input forms and a checkbox:
What I would like to have is the following (created via PowerPoint):
So if the users click the checkbox the webform should automatically disable the second input form and copy the value and/or the placeholder of the first input form. So briefly speaking: If the users click the checkbox the second input form should be exactly like the first one, except that it is disabled.
Unfortunately I have no clue how to do this. By now my code looks like this:
Input field 1 (key user) + checkbox:
<div class="form-group">
<label class="control-label col-sm-2" for="keyuser">Key-User:</label>
<div class="col-sm-10">
<input type="keyuser" class="form-control" id="keyuser" placeholder="Username Key-User">
<div class="checkbox">
<label onclick="checkbox()">
<input type="checkbox">
</label>Is the affected user
</div>
</div>
Input field 2 (affected user):
<div class="form-group">
<label class="control-label col-sm-2" for="affuser">Affected User:</label>
<div class="col-sm-10">
<input type="affuser" class="form-control" id="affuser" placeholder="Username affected user">
</div>
Checkbox() [it does not work at all right now]:
function checkbox() {
"use strict";
if (check === "False") {
check = "True";
$('#affuser').attr('placeholder', 'Username Key-User');
} else {
check = "False";
$('#affuser').attr('placeholder', 'Username affected user');
}
}
How can I implement the functions mentioned above?
There are some changes that I would want to implement to your script rightaway:
Do not use inline JS. Instead, create an onchange event handler for the checkbox (not the label element)
Use IDs for your checkbox so that your <label> will be functioanlly attached to it.
For the JS, it's quite simple: When an onchange event is registered on the checkbox element, evaluate if it is checked or not, by simply evaluating the .is(':checked') boolean:
If checked:
disable the #affuser element using .prop('disabled', true)
update the placeholder attribute using .attr('placeholder', ...)
If unchecked:
enable the aforementioned element using .prop('disabled', false)
update the placeholder attribute using, again, .attr('placeholder', ...)
$(function() {
$('#checkbox1').on('change', function() {
if($(this).is(':checked')) {
$('#affuser')
.prop('disabled', true)
.attr('placeholder', $('#keyuser').attr('placeholder'));
} else {
$('#affuser')
.prop('disabled', false)
.attr('placeholder', 'Username affected user');
}
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-sm-2" for="keyuser">Key-User:</label>
<div class="col-sm-10">
<input type="keyuser" class="form-control" id="keyuser" placeholder="Username Key-User">
<div class="checkbox">
<label for="checkbox1">
<input type="checkbox" id="checkbox1">
</label>Is the affected user
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="affuser">Affected User:</label>
<div class="col-sm-10">
<input type="affuser" class="form-control" id="affuser" placeholder="Username affected user">
</div>
</div>

JavaScript - set form input attribute in 'for' loop

This is my first real-world JavaScript project. Please be kind...
I'm creating a form with required fields. With JavaScript, I am collecting the required fields as objects in an Array, each object having the properties "object" (the HTML objects themselves, from which I can get object.id and object.value) "description" (to display to users) and "error" (the HTML objects beneath each input field where corresponding validation errors appear).
Then I have a function (to be used onBlur, for instant feedback) that checks to see if the value of the field is null, and if so, it displays the validation error beneath the corresponding field.
I'm trying to set the onblur attribute for each input field using a FOR loop that runs through the array of required fields. I have a setAttribute statement that works perfectly if I create an individual statement for each object in the Array, individually. But as soon as I change it to a FOR loop, the onblur event for ANY field pops up the validation error for the FIRST input field, only. This has got to be a freshman mistake, but I've searched high and low and rewritten this thing ten different ways and can't make it work with a loop...
I put my code in a Fiddle so you can see it -- but it doesn't actually work in the fiddle, only in my local dev environment (maybe that indicates another problem?). Here's the code:
//create array with constructor to identify all required fields
var allRequired = [];
function RequiredField(theID, theDescription) {
this.object = document.getElementById(theID);
this.description = theDescription;
this.error = document.getElementById("error-" + theID);
allRequired.push(this);
}
var fieldFname = new RequiredField("fname", "First Name");
var fieldLname = new RequiredField("lname", "Last Name");
var fieldEmail = new RequiredField("email", "Email");
var fieldPhone = new RequiredField("phone", "Phone");
var fieldRole = new RequiredField("role", "Desired Role");
var fieldPortfolio = new RequiredField("portfolio", "Portfolio/Website URL");
function requireField(theDescription, theValue, theError) {
if (theValue === "") {
theError.innerHTML = "<p>" + theDescription + " is required.</p>";
} else {
theError.innerHTML = "";
}
} //end function
for (i = 0; i < allRequired.length; i++) {
allRequired[i].object.setAttribute("onBlur", "requireField(allRequired[i].description, allRequired[i].object.value, allRequired[i].error);");
}
/* THIS WORKS IN MY LOCAL DEV ENVIRONMENT...
allRequired[0].object.setAttribute("onBlur", "requireField(allRequired[0].description, allRequired[0].object.value, allRequired[0].error);");
allRequired[1].object.setAttribute("onBlur", "requireField(allRequired[1].description, allRequired[1].object.value, allRequired[1].error);");
allRequired[2].object.setAttribute("onBlur", "requireField(allRequired[2].description, allRequired[2].object.value, allRequired[2].error);");
allRequired[3].object.setAttribute("onBlur", "requireField(allRequired[3].description, allRequired[3].object.value, allRequired[3].error);");
allRequired[4].object.setAttribute("onBlur", "requireField(allRequired[4].description, allRequired[4].object.value, allRequired[4].error);");
allRequired[5].object.setAttribute("onBlur", "requireField(allRequired[5].description, allRequired[5].object.value, allRequired[5].error);");
*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form-careers" id="form-careers" action="form-process.php" enctype="multipart/form-data" onsubmit="return validateForm()" method="post">
<div class="form_labels">
<p>
<label for="fname">First Name:</label>
</p>
</div>
<div class="form_inputs">
<p>
<input type="text" name="fname" id="fname" required />
</p>
<div class="error" id="error-fname"></div>
</div>
<div class="form_labels">
<p>
<label for="lname">Last Name:</label>
</p>
</div>
<div class="form_inputs">
<p>
<input type="text" name="lname" id="lname" required />
</p>
<div class="error" id="error-lname"></div>
</div>
<div class="form_labels">
<p>
<label for="email">Email:</label>
</p>
</div>
<div class="form_inputs">
<p>
<input type="email" name="email" id="email" required />
</p>
<div class="error" id="error-email"></div>
</div>
<div class="form_labels">
<p>
<label for="phone">Phone:</label>
</p>
</div>
<div class="form_inputs">
<p>
<input type="tel" name="phone" id="phone" placeholder="###-###-####" pattern="\d{3}[\-]\d{3}[\-]\d{4}" required />
</p>
<div class="error" id="error-phone"></div>
</div>
<div class="form_labels">
<p>
<label for="role">Desired Role:</label>
</p>
</div>
<div class="form_inputs">
<p>
<input type="text" name="role" id="role" required />
</p>
<div class="error" id="error-role"></div>
</div>
<div class="form_labels">
<p>
<label for="portfolio">Portfolio/Website:</label>
</p>
</div>
<div class="form_inputs">
<p>
<input type="url" name="portfolio" id="portfolio" placeholder="http://" pattern="[a-z0-9.-]+\.[a-z]{2,63}$" required />
</p>
<div class="error" id="error-portfolio"></div>
</div>
<div class="clearboth"></div>
<input type="hidden" name="formtype" id="formtype" value="careers">
<div class="form_labels">
<p> </p>
</div>
<div class="form_inputs">
<a href="#">
<input type="submit" value="Submit" class="btn-red">
</a>
</div>
</form>
If someone would help point me in the right direction I would really appreciate it.
Code
for (i = 0; i < allRequired.length; i++) {
allRequired[i].object.setAttribute("onBlur", "requireField(allRequired[i].description, allRequired[i].object.value, allRequired[i].error);");
}
sets onblur event with value like requireField(allRequired[i].description.
So - what is it - i? No one knows.
Proper code is:
for (i = 0; i < allRequired.length; i++) {
allRequired[i].object.setAttribute("onBlur", "requireField(allRequired[" +i + "].description, allRequired[" + i + "].object.value, allRequired[" + i + "].error);");
}
See? I get real i value for each iteration.
As u_mulder said concat problem.
As for code I suggest to look up factory functions. It's more natural javascript then constructor.

Categories

Resources