How do I use document.getElementById from an input in a modal? - javascript

I have a homemade modal (not bootstrap) that I have inserted a form into that I need to use JS to retrieve the values of:
<div id="openModal" class="modalDialog">
<div>X
<h2>Please contact me with any questions or to request a Free Home Market Analysis</h2>
<!--<form id="contact_form">-->
<p id="fname" class="form_items">
<input type="text" name="fname" id="fname" placeholder="First Name" required />
</p>
<p id="lname" class="form_items">
<input type="text" name="lname" id="lname" placeholder="Last Name" required />
</p>
<p id="email" class="form_items">
<input type="email" name="email" id="email" placeholder="Email" required />
</p>
<p id="phone" class="form_items">
<input type="tel" name="phone" id="phone" placeholder="Telephone" />
</p>
<p id="comments" class="form_items">
<textarea rows="4" cols="50" name="message" placeholder="Comments" id="message"></textarea>
</p>
<p>
<button class="submit" type="submit" onclick="submitForm();">Submit</button>
</p>
<span id="status"></span>
<!--</form>-->
</div>
</div>
<input type="text" id="test"/>
<button onclick="submitForm()">Hi</button>
The test input and button is an example of what does work, when outside of the modal. Here is the JS:
function submitForm(){
var xmlhttp = new XMLHttpRequest();
var fn = document.getElementById('fname').value;
var ln = document.getElementById('lname').value;
var e = document.getElementById('email').value;
var p = document.getElementById('phone').value;
var m = document.getElementById('message').value;
alert(fn);
var test = document.getElementById('test').value;
alert(test);
}
The first alert(fn) alerts "undefined" while the second alert(test) alerts the value I enter into the test input box.
Why is this and what is the workaround? I tried making a jsfiddle: https://jsfiddle.net/k1g9dq7w/ but the Fiddle doesn't work, maybe someone knows more about JsFiddle and why this is.

Remove id from <p>. id is unique in the document.

id of <p> tag and <input> tag should be different.
In your case, getElementById('fname') method accessed the <p> tag because it is the first tag whose id is equal to 'fname'.

It is true that you need to remove the unique id attribute from the <p> element.
However if you test it with only that change it will still not work on the given jsFiddle sample. you need to change the jsFiddle javascript settings by clicking on the javascript button over the paragraph, and changing load type from 'onload' to 'No wrap ~In head' so it will treat the javascript as if it is in the <head> area of the html, Rather than their default which is executing the script onLoad.

Related

compare the value of two form email fields

I have created a form requiring email validation. So user must type in their email address twice and if they don't match they won't be able to submit. I did this by simply comparing the values of email fields 1 and 2. If they match "disabled" is removed from the submit button.
All was working perfectly when I had the value set to "Insert your email address and "confirm your email address again". However, so that the user does not have to delete that text, I removed the value and used "placeholder" in the HTML instead.
The problem now is that the moment you type anything it's returning as true. I guess it's seeing the blank values as the same, but it's not picking up on the changes to the value as the user types it in.
Why are the two fields always returning as a match?
<html>
<body>
<form class="theForm">
<p> Subscribe to my mailing list</p>
<input type="text" id="name" class="fields" name="name" placeholder="Name">
<input type="text" id="email1" class="fields" name="email" placeholder="Email Address" >
<input type="text" id="email2" class="fields" placeholder="Confirm Email Address" >
<input name="submit" id="submit" class="fields" type="submit" disabled value="Email Addresses
Do Not Match">
</form>
<script>
function verify (){
console.log(`email1.value: ${email1}: Email2: ${email2}`);
if(document.getElementById("email1").value === document.getElementById("email2").value) {
document.getElementById("submit").removeAttribute("disabled");
document.getElementById("submit").style.backgroundColor = "#004580";
document.getElementById("submit").style.cursor = "pointer";
} else {
document.getElementById("submit").setAttribute("disabled", "disabled");
}
}
$(".fields").on("change paste keyup", verify);
</script>
</body>
</html>
try this
<html>
<body>
<form class="theForm">
<p> Subscribe to my mailing list</p>
<input type="text" id="name" class="fields" name="name" placeholder="Name">
<input type="text" id="email1" class="fields" name="email" placeholder="Email Address" >
<input type="text" id="email2" class="fields" placeholder="Confirm Email Address" >
<input id="submit" type="button" onclick="verify()" value="click">
</form>
<script>
function verify()
{
if(document.getElementById("email1").value === document.getElementById("email2").value) {
alert("matched")
} else {
document.getElementById("submit").setAttribute("disabled", "disabled");
alert("not matched")
}
}
</script>
</body>
</html>
This worked for me:
Change the email inputs to [type='email'].
Add the required attribute to #email1.
Add a check to the validity of #email1 in your conditional.
Reset styles to initial (or what you prefer) if the button is reset back to 'disabled'.
Use 'input' event to get the the values updating on every keystroke, 'change' only fires on 'blur' or when the form is submitted.
It'd end up looking like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<form class="theForm">
<p> Subscribe to my mailing list</p>
<input type="text" id="name" class="fields" name="name" placeholder="Name">
<input type="email" id="email1" class="fields" name="email" placeholder="Email Address" required>
<input type="email" id="email2" class="fields" placeholder="Confirm Email Address" >
<input name="submit" id="submit" class="fields" type="submit" disabled value="Email Addresses Do Not Match">
</form>
<script>
function verify (){
console.log(`email1: ${email1.value}: Email2: ${email2.value}`);
if(document.getElementById("email1").checkValidity() && document.getElementById("email1").value === document.getElementById("email2").value) {
document.getElementById("submit").removeAttribute("disabled");
document.getElementById("submit").style.backgroundColor = "#004580";
document.getElementById("submit").style.cursor = "pointer";
} else {
document.getElementById("submit").setAttribute("disabled", "disabled");
document.getElementById("submit").style.backgroundColor = "initial";
document.getElementById("submit").style.cursor = "initial";
}
}
$(".theForm").on("input paste keyup", "input[type=email]", verify);
</script>
</body>
</html>
MDN Docs for input and change events:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
Instead of:
$(".fields").on("change paste keyup", verify)
Try:
$(".fields").blur(verify)
EDIT:
How about:
$("#email2").blur(verify)
?

How to enable autocomplete in <input > with <label ><input ><button >

I am not web developer, but I have a task to add autocomplete function for an input box. Please treat me as a very beginner.
<div>
<label id="email_label" for="send_email" style="padding-right:5px">
Send Email:
</label>
<input id="send_email" type="text" placeholder="e.g. xx.yy#zz.com" />
<button id="ack" onclick="requestAck()">
Request
</button>
</div>
requestAck() is a javascript function sending a email to address given by user (i.e. address in <input >). I am trying to add a flag in <input autocomplete="on" ...>, but it doesn't work. Perhaps because it's not in a <form></form> environment.
Could you help me to modify this code adding autocomplete (from cache) without changing other functions. Many thanks!
Try setting the property name="email" on the input tag, without that set the browser doesn't know what's supposed to autocomplete the field with :)
protip: I warmly suggest you to set the type of the input to email with type="email" instead of text, it's not required but it will help validating the input!
check this code:
<div>
<label id="email_label" for="send_email" style="paddingright:5px">Send Email:</label>
<input id="send_email" type="email" name="email" placeholder="e.g. xx.yy#zz.com" />
<button id="ack" onclick="requestAck()">Request</button>
</div>
EDIT: Final solution discussed in comments
<form onsubmit="submitForm(event)">
<label id="email_label" for="send_email" style="padding-right:5px">Send Email:</label>
<input id="send_email" type="email" autocomplete="email" name="email" placeholder="e.g. xx.yy#zz.com" />
<button id="ack" type="submit">Request</button>
</form>
<script>
function submitForm(e) {
e.preventDefault(); // this prevents the page from reloading
requestAck();
}
//dummy function so the javascript won't crash:
function requestAck() {}
</script>
Working example: https://codesandbox.io/s/focused-cray-ubkw4

Cannot find web element on div popup when using nodejs and webdriverjs

Please help me, I stuck at likely simple task. I'm learning to webdriverjs , so I wrote a small code to register an account on FitBit site at url: www.fitbit.com/signup, after input my email and password, there is an div popup show up and ask user to fill all required field. Problem comes here, I cannot 'sendkeys' or 'click' on First Name field, could you please help me out?
my code is very simple:
const webdriver = require('selenium-webdriver');
const driver = new webdriver.Builder()
.forBrowser('firefox')
.build();
const By = webdriver.By;
// ask the browser to open a page
driver.navigate().to('https://www.fitbit.com/signup');
//Enter Email
driver.findElement(By.className('field email')).sendKeys('thisisatest#yopmail.com');
//Enter Password
driver.findElement(By.className('field password')).sendKeys('Abcd1234');
//Check check box
driver.findElement(By.id('termsPrivacyConnected')).click();
//Click Continue button
driver.findElement(By.xpath("//button[#type='submit' and #tabindex='16']")).click();
//Input First Name
driver.sleep(3000);
driver.findElement(By.xpath('//input[#id="firstName"]')).click();
driver.findElement(By.xpath('//input[#id="firstName"]')).sendKeys('why not input');
Depending on if this is a popup, a frame or another window you need a different SwitchTo() command. See: http://toolsqa.com/selenium-webdriver/switch-commands/ or here: http://learn-automation.com/handle-frames-in-selenium/
Now you added your HTML it is clear that that you don't have to Switch to fill in the popup fields. I translated your code to C# and use Chromedriver instead of Firefox and there where no problems filling in the Firstname and Lastname. So basicly nothing is wrong with your code.
Are you getting any error messages?
There is no window here, that's a tag, I posted its source code here for your reference
<section class="wrapper profile common-form">
<div class="panel panel-profile">
<h1 class="headline">
Tell Us About Yourself
</h1>
<p class="explain">
We use this information to improve accuracy.
</p>
<form method="post" autocomplete="off" name="completeProfile" action="https://www.fitbit.com/user/profile/complete" id="completeProfile" class="form">
<input name="_eventName" type="hidden" value="signupAndCompleteProfile" />
<input name="redirect" type="hidden" value="" />
<input name="csrfToken" type="hidden" value="84764c8b4da04c85a4541e49947240d0" />
<fieldset class="info-personal">
<dl class="field-group">
<dd class="left-cell">
<label class="field-label">
Name
</label>
<input autocomplete="off" tabindex="1" name="firstName" id="firstName" placeholder="First Name" type="text" class="field firstName" />
</dd>
<dd class="right-cell">
<label class="field-label"> </label>
<input autocomplete="off" tabindex="1" name="lastName" id="lastName" placeholder="Last Name" type="text" class="field lastName" />
</dd>
</dl>
<div class="clear"></div>
</fieldset>
</section>

how to get set of input boxes values using getElemntById?

I have set of input boxes to add names and designaions.and iwant to print those in a <p> tag when user click print button. how to proceed.
<div class="form-group">
<label for="inputRegNo" >Name & Designation<span style="color:#c0392b;padding-left:5px;">*</span></label>
<div class="form-group">
<input required type="text" name="fname[]" class="fname" onkeyUp="document.getElementById('refa5').innerHTML = this.value" placeholder="Name" />
<input required type="text" name="lname[]" placeholder="Designation" />
</div>
</div>
<div class="form-group">
<label for="inputRegNo" ></label>
<div class="form-group">
<input type="text" name="fname[]" placeholder="Name" class="fname" onkeyUp="document.getElementById('refa5').innerHTML = this.value" />
<input type="text" name="lname[]" placeholder="Designation" />
</div>
</div>
print
<div>
<label>Name & Designation</label>
<p id="refa5"> - </p>
</div>
its looks you are new in javascript.. it's simple give the name to all the input field like
<input type="text/checkbox" name="txtName">
and in javascript you can access this field value by
<script type="text/javascript">
var name = document.getElementsByName("txtName");
</script>
if you wish to print the element on button click simply specify their click event on javascript like
function onClick() {
alert("helo from click function");
}
and then on button ..
<input type="button" onclick="onClick()">
w3schools is a great resource for this. Here is some example code on how to do this :
<button onclick="myFunction()">Click me</button>
<input id="inputID"></input>
<p id="demo"></p>
<script>
function myFunction() {
var inputID = document.getElementById("inputID").value;
document.getElementById("demo").innerHTML = inputID;
}
</script>
What the code above does is it takes the value of an input, then it sets the innerHTML of a <p> element to it. You can obviously do this with other things like <h1> elements as well.

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