I am getting this error "Uncaught TypeError: Cannot set property 'onclick' of null
at index.html:73" and I can't seem to navigate past through it. an help on this one please, it should, when I click button next bring up the next form instead there is nothing and in the chrome debug option that's where I noticed that error.
<body>
<div class="container">
<form id="Form1">
<h3>Create Account</h3>
<input type="text" placeholder="Email" required>
<input type="password" placeholder="Password" required>
<input type="password" placeholder="Confirm Password" required>
<div class="btn-box">
<button type="button" id="Next1">Next</button>
</div>
</form>
<form id="Form2">
<h3>Social Links</h3>
<input type="text" placeholder="Medium">
<input type="text" placeholder="Github">
<input type="text" placeholder="LinkedIn">
<div class="btn-box">
<button type="button" id="Back1">back</button>
<button type="button" id="Next2">Next</button>
</div>
</form>
<form id="Form3">
<h3>Personal Info</h3>
<input type="text" placeholder="First Name" required>
<input type="text" placeholder="Last Name" required>
<input type="text" placeholder="Mobile No." required>
<div class="btn-box">
<button type="button" id="Back2">back</button>
<button type="Submit">Submit</button>
</div>
</form>
<div class="step-row">
<div id="progress"></div>
<div class="step-col">Step 1</div>
<div class="step-col">Step 2</div>
<div class="step-col">Step 3</div>
</div>
</div>
<script>
var Form1 = document.getElementById(Form1);
var Form2 = document.getElementById(Form2);
var Form3 = document.getElementById(Form3);
var Next1 = document.getElementById(Next1);
var Next2 = document.getElementById(Next2);
var Back1 = document.getElementById(Back1);
var Back2 = document.getElementById(Back2);
var progress = document.getElementById("progress");
Next1.onclick = function() {
Form1.style.left = "-450px";
Form2.style.left = "40px";
progress.style.width = "240px";
}
Back1.onclick = function() {
Form1.style.left = "40px";
Form2.style.left = "450px";
progress.style.width = "120px";
}
Next2.onclick = function() {
Form2.style.left = "-450px";
Form3.style.left = "40px";
progress.style.width = "360px";
}
Back2.onclick = function() {
Form1.style.left = "40px";
Form2.style.left = "450px";
progress.style.width = "240px";
}
</script>
</body>
</html>
Try something like following:-
var Form1 = document.getElementById('Form1');
var Form2 = document.getElementById('Form2');
var Form3 = document.getElementById('Form3');
var Next1 = document.getElementById('Next1');
var Next2 = document.getElementById('Next2');
var Back1 = document.getElementById('Back1');
var Back2 = document.getElementById('Back2');
Related
I have been refactoring some of my innerHTML content within a form to make it more readable. Before, I had one lump innerHTML which was hard to read, however worked and allowed updating to localStorage.
I gave each div wrapper its own unique ID so that I could change the innerHTML value, in order to make everything neater and readable, this worked fine but when I try to edit my form now it gives me an error of cannot set property 'fname' of undefined. When I revert it back to the lump html it edits fine?
My knowledge is limited of how JS works, so can anyone explain why this might be happening, and is there a resolution?
Here's my code and edit handler (simplified), it's difficult to show on this as it's using localStorage but hopefully it's at least helpful:
$(document).on('change keyup', '.required', function(e) {
var disabled = true;
$(".required").each(function() {
var value = this.value;
if (!(value) || (value.trim() === '') || ($(this).hasClass('is-invalid'))) {
disabled = false;
$('.toggle-disabled').prop("disabled", true);
}
});
if (disabled) {
$('.toggle-disabled').prop("disabled", false);
}
});
var bookings = JSON.parse(localStorage.getItem("bookings")) || [];
$("#submit").click(function() {
var newBookings = {
id: new Date().getTime(),
fname: $('#fname').val(),
lname: $('#lname').val(),
}
bookings.push(newBookings);
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
showBooking();
document.getElementById('formSuccess').style.display = "block";
});
$(document).on('click', '#edit', function(e) {
e.preventDefault();
var parent_form = $('this.form');
var fname = parent_form.find('.fname').val();
var lname = parent_form.find('.lname').val();
let i = bookings.findIndex(booking => booking.id == $(this).data("id"));
bookings[i].fname = fname;
bookings[i].lname = lname;
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
alert('Form updated!');
window.location.reload();
showBooking();
});
function showBooking() {
var bookingResult = document.getElementById("result");
var ul = document.createElement("ul");
bookingResult.innerHTML = `<h3 class="text-center">Your Bookings</h3>`;
for (let i = 0; i < bookings.length; i++) {
bookingResult.innerHTML += `
<div class="card card-body bg-light m-4">
<div class="row">
<p>Owner name: ${bookings[i].fname + " " + bookings[i].lname}</p>
</div>
<div class="row">
<div class="d-grid gap-2 d-md-block">
<button onclick="editBooking(${i})" class="col-md-4 btn btn-outline-danger ">Edit</button>
<button onclick="deleteBooking(${i})" class="col-md-4 btn btn-danger text-light ">Delete</button>
</div>
</div>
</div>`;
}
}
function editBooking(i) {
$('#result').hide();
var fnameEdit = document.getElementById("fnameEdit");
var lnameEdit = document.getElementById("lnameEdit");
var editButton = document.getElementById("editBtn");
fnameEdit.innerHTML = `<input type="text" class="fname form-control required" data-id="${bookings[i].id}" placeholder="First Name" name="${bookings[i].fname}" value="${bookings[i].fname}" required>`;
lnameEdit.innerHTML = `
<input type="text" class="lname form-control required" data-id="${bookings[i].id}" placeholder="Last Name" name="${bookings[i].lname}" value="${bookings[i].lname}" required>`;
editButton.innerHTML = `<div class="d-grid gap-2 d-md-block">
<input id="edit" class="btn btn-danger toggle-disabled" type="submit" value="Edit">
Cancel
</div>`;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<form id="regForm" name="regForm" action="" class="col-md-6">
<div class="row">
<div id="fnameEdit" class="col-md-6">
<input type="text" class="input form-control required" id="fname" placeholder="First Name" name="fname" required>
</div>
<div id="lnameEdit" class="col-md-6">
<input type="text" class="input form-control required" id="lname" placeholder="Last Name" name="lname" required>
</div>
</div>
<div id="editBtn">
<div class="col-md-6">
<input id="submit" class="btn btn-danger toggle-disabled" type="submit" value="Submit">
</div>
</div>
</form>
<div class="col-md-6">
<div id="result" class="row"></div>
<div id="currentItem" class="row"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
The first issue is described in the comment by #Swati (i.e.: $(this).closest('form'))
As a consequence, the second issue is related to the anonymous function you use inside .findIndex():
Change this part from:
let i = bookings.findIndex(booking => booking.id == $(this).data("id"));
to:
let i = bookings.findIndex(booking => booking.id == parent_form.find('.fname').data("id"));
$(document).on('change keyup', '.required', function(e) {
var disabled = true;
$(".required").each(function() {
var value = this.value;
if (!(value) || (value.trim() === '') || ($(this).hasClass('is-invalid'))) {
disabled = false;
$('.toggle-disabled').prop("disabled", true);
}
});
if (disabled) {
$('.toggle-disabled').prop("disabled", false);
}
});
var bookings = JSON.parse(localStorage.getItem("bookings")) || [];
$("#submit").click(function() {
var newBookings = {
id: new Date().getTime(),
fname: $('#fname').val(),
lname: $('#lname').val(),
}
bookings.push(newBookings);
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
showBooking();
document.getElementById('formSuccess').style.display = "block";
});
$(document).on('click', '#edit', function(e) {
e.preventDefault();
var parent_form = $(this).closest('form');
var fname = parent_form.find('.fname').val();
var lname = parent_form.find('.lname').val();
let i = bookings.findIndex(booking => booking.id == parent_form.find('.fname').data("id"));
bookings[i].fname = fname;
bookings[i].lname = lname;
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
alert('Form updated!');
window.location.reload();
showBooking();
});
function showBooking() {
var bookingResult = document.getElementById("result");
var ul = document.createElement("ul");
bookingResult.innerHTML = `<h3 class="text-center">Your Bookings</h3>`;
for (let i = 0; i < bookings.length; i++) {
bookingResult.innerHTML += `
<div class="card card-body bg-light m-4">
<div class="row">
<p>Owner name: ${bookings[i].fname + " " + bookings[i].lname}</p>
</div>
<div class="row">
<div class="d-grid gap-2 d-md-block">
<button onclick="editBooking(${i})" class="col-md-4 btn btn-outline-danger ">Edit</button>
<button onclick="deleteBooking(${i})" class="col-md-4 btn btn-danger text-light ">Delete</button>
</div>
</div>
</div>`;
}
}
function editBooking(i) {
$('#result').hide();
var fnameEdit = document.getElementById("fnameEdit");
var lnameEdit = document.getElementById("lnameEdit");
var editButton = document.getElementById("editBtn");
fnameEdit.innerHTML = `<input type="text" class="fname form-control required" data-id="${bookings[i].id}" placeholder="First Name" name="${bookings[i].fname}" value="${bookings[i].fname}" required>`;
lnameEdit.innerHTML = `
<input type="text" class="lname form-control required" data-id="${bookings[i].id}" placeholder="Last Name" name="${bookings[i].lname}" value="${bookings[i].lname}" required>`;
editButton.innerHTML = `<div class="d-grid gap-2 d-md-block">
<input id="edit" class="btn btn-danger toggle-disabled" type="submit" value="Edit">
Cancel
</div>`;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.bundle.min.js"></script>
<form id="regForm" name="regForm" action="" class="col-md-6">
<div class="row">
<div id="fnameEdit" class="col-md-6">
<input type="text" class="input form-control required" id="fname" placeholder="First Name" name="fname" required>
</div>
<div id="lnameEdit" class="col-md-6">
<input type="text" class="input form-control required" id="lname" placeholder="Last Name" name="lname" required>
</div>
</div>
<div id="editBtn">
<div class="col-md-6">
<input id="submit" class="btn btn-danger toggle-disabled" type="submit" value="Submit">
</div>
</div>
</form>
<div class="col-md-6">
<div id="result" class="row"></div>
<div id="currentItem" class="row"></div>
</div>
I ended up solving this problem eventually, I hadn't given the attributes a new ID and somehow, that sorted the issue. I removed the innerHTML and replaced with setAttribute methods which work fine.
Thanks for help!
Something along these lines:
var fname = document.getElementById("fname");
var lname = document.getElementById("lname");
var editButton = document.getElementById("editBtn");
fname.setAttribute('data-id', bookings[i].id);
fname.setAttribute('value', bookings[i].fname);
lname.setAttribute('data-id', bookings[i].id);
lname.setAttribute('value', bookings[i].lname);
editButton.innerHTML = `<div class="d-grid gap-2 d-md-block">
<input data-id="${bookings[i].id}" id="edit" class="btn btn-danger toggle-disabled" type="submit" value="Edit" disabled>
Cancel
</div>`;
So, I was working on a simple Form validation. But after entering the value when I try to get the value from the input element in the console using JavaScript, it is returning blank.
Where am I going wrong:
Here is the code:
var x = document.getElementById("fName").value;
var y = document.getElementById("lName").value;
var z = document.getElementById("emailId").value;
function myFunction() {
document.getElementById("demo").innerHTML = x;
console.log(x);
}
<h1 class="jumbotron">Simple Form Validation</h1>
<div class="container-fluid">
<form>
<label>First Name: <input type="text" value="" id="fName" placeholder="ex: Shubham"></label><br />
<label>Second Name: <input id="lName" value="" type="text" placeholder="ex: Bhatt"></label><br />
<label>Email Id: <input id="emailId" value="" type="alphanumeric" placeholder="ex: abc#gmail.com"></label> <br />
<input type="button" value="Submit" id="submitBtn" class="btn btn-primary" onclick="myFunction()">
<p id="demo"></p>
</form>
</div>
/*
var x = document.getElementById("fName").value;
var y = document.getElementById("lName").value;
var z = document.getElementById("emailId").value;
*/
function myFunction(){
var x = document.getElementById("fName").value;
var y = document.getElementById("lName").value;
var z = document.getElementById("emailId").value;
document.getElementById("demo").innerHTML = x;
console.log(x);
}
<h1 class="jumbotron">Simple Form Validation</h1>
<div class="container-fluid">
<form>
<label>First Name: <input type="numeric" value="" id="fName" placeholder="ex: Shubham"></label><br />
<label>Second Name: <input id="lName" value="" type="text" placeholder="ex: Bhatt"></label><br />
<label>Email Id: <input id="emailId" value="" type="alphanumeric" placeholder="ex: abc#gmail.com"></label> <br />
<input type="button" value="Submit" id="submitBtn" class="btn btn-primary" onclick="myFunction()">
<p id="demo"></p>
</form>
</div>
Move variable
Global -> Local
You are getting the values outside the function, in other words, you try to get the values of the input fields before you enter anything there. Try this instead of your javascript
<script>
function myFunction(){
var x = document.getElementById("fName").value;
var y = document.getElementById("lName").value;
var z = document.getElementById("emailId").value;
document.getElementById("demo").innerHTML = x;
console.log(x);
}
</script>
You are extracting the values when the documents get ready. But you have to get the value when users submit the form.So you need to get the values inside the function try using this:
function myFunction(){
var x = document.getElementById("fName").value;
var y = document.getElementById("lName").value;
var z = document.getElementById("emailId").value;
document.getElementById("demo").innerHTML = x;
console.log(x);
}
You only querying your values once as you load the page. What you can do is to query the fields and value inside your function. Or better: only check the values in your function and leave the getElementById still outside, like this:
var x = document.getElementById("fName");
var y = document.getElementById("lName");
var z = document.getElementById("emailId");
function myFunction() {
document.getElementById("demo").innerHTML = x.value;
console.log(x.value);
}
<h1 class="jumbotron">Simple Form Validation</h1>
<div class="container-fluid">
<form>
<label>First Name: <input type="text" value="" id="fName" placeholder="ex: Shubham"></label><br />
<label>Second Name: <input id="lName" value="" type="text" placeholder="ex: Bhatt"></label><br />
<label>Email Id: <input id="emailId" value="" type="alphanumeric" placeholder="ex: abc#gmail.com"></label> <br />
<input type="button" value="Submit" id="submitBtn" class="btn btn-primary" onclick="myFunction()">
<p id="demo"></p>
</form>
</div>
As the title would suggest I keep getting that error when trying to test out a basic script which would "read" form inputs and make them variables to use later on.
HTML:
<script type="text/javascript" language="javascript"
src="./js/lisearch.js"></script>
<form name="search" action="" method="post">
<h2>Include:</h2>
<div id="formtitle" class="formdiv">
<p> Current Job Title:</p><input id="jtitle" type="text" name="jobtitle" placeholder="Demand planner, Supply planner">
</div>
<div id="formcompany" class="formdiv">
<p> Current Company:</p><input id="cmpy" type="text" name="company" placeholder="GSK OR Danone">
</div>
<div id="formkeywords" class="formdiv">
<p> Keywords:</p><input id="kwrd" type="text" name="keywords" placeholder="(SAP OR JDE) AND FMCG">
</div>
<div id="formfirst" class="formdiv">
<p> First Name:</p><input id="fname" type="text" name="first">
</div>
<div id="formlast" class="formdiv">
<p> Last Name:</p><input id="lname" type="text" name="last">
</div>
<hr>
<h2> Exclude:</h2>
<div id="formnottitle" class="formdiv">
<p> Current Job Title:</p><input id="njtitle" type="text" name="notjobtitle" placeholder="Manager OR Consultant">
</div>
<div id="formnotcompany" class="formdiv">
<p> Current Company:</p><input id="ncmpy" type="text" name="notcompany" placeholder="Coke OR Pepsi">
</div>
<div id="formnotkeywords" class="formdiv">
<p> Keywords:</p><input id="nkwrd" type="text" name="notkeywords" placeholder="Recruiter OR Recruitment">
</div>
<div id="submit" class="formdiv">
<input type="button" value="Create Search" onclick="onclick()">
</div>
<div id="output" class="formdiv">
<input type="text" name="output">
</div>
</form>
JS:
var company;
var jobtitle;
var keywords;
var fname;
var lname;
var notcompany;
var notjobtitle;
var notkeywords;
function onclick() {
company = document.getElementById('cmpy').value;
jobtitle = document.getElementById('jtitle').value;
keywords = document.getElementById('kwrd').value;
fname = document.getElementById('fname').value;
lname = document.getElementById('lname').value;
notcompany = document.getElementById('ncmpy').value;
notjobtitle = document.getElementById('njtitle').value;
notkeywords = document.getElementById('nkwrd').value;
test();
}
function test() {
alert(company + jobtitle + keywords + fname + lname + notcompany + notjobtitle + notkeywords);
}
As you can probably tell I am really new to all this but can't seem to figure this out, any help appreciated.
Thanks,
This kind of message you get when doing recursive calls and get stuck somewhere in a cycle. in your case rename onclick() function to something else, that's it!
Here I made a plunker
function toto() {
company = document.getElementById('cmpy').value;
jobtitle = document.getElementById('jtitle').value;
keywords = document.getElementById('kwrd').value;
fname = document.getElementById('fname').value;
lname = document.getElementById('lname').value;
notcompany = document.getElementById('ncmpy').value;
notjobtitle = document.getElementById('njtitle').value;
notkeywords = document.getElementById('nkwrd').value;
test();
}
function test() {
alert(company + jobtitle + keywords + fname + lname + notcompany + notjobtitle + notkeywords);
}
and
<input type="button" value="Create Search" onclick="toto()">
put function test at the top of your js code so that onclick() knows what it is when the event handler is assigned.
Edit: Additional feedback:
The test function isn't even needed. Just insert the alert code into the onclick function.
edit: Moving the script tags shouldn't actually have any effect. I am not sure what is going wrong here.
Edit:solved it
<form name="search" action="" method="post">
<h2>Include:</h2>
<div id="formtitle" class="formdiv">
<p> Current Job Title:</p><input id="jtitle" type="text" name="jobtitle" placeholder="Demand planner, Supply planner">
</div>
<div id="formcompany" class="formdiv">
<p> Current Company:</p><input id="cmpy" type="text" name="company" placeholder="GSK OR Danone">
</div>
<div id="formkeywords" class="formdiv">
<p> Keywords:</p><input id="kwrd" type="text" name="keywords" placeholder="(SAP OR JDE) AND FMCG">
</div>
<div id="formfirst" class="formdiv">
<p> First Name:</p><input id="fname" type="text" name="first">
</div>
<div id="formlast" class="formdiv">
<p> Last Name:</p><input id="lname" type="text" name="last">
</div>
<hr>
<h2> Exclude:</h2>
<div id="formnottitle" class="formdiv">
<p> Current Job Title:</p><input id="njtitle" type="text" name="notjobtitle" placeholder="Manager OR Consultant">
</div>
<div id="formnotcompany" class="formdiv">
<p> Current Company:</p><input id="ncmpy" type="text" name="notcompany" placeholder="Coke OR Pepsi">
</div>
<div id="formnotkeywords" class="formdiv">
<p> Keywords:</p><input id="nkwrd" type="text" name="notkeywords" placeholder="Recruiter OR Recruitment">
</div>
<div id="submit" class="formdiv">
<input type="button" id="onclick" value="Create Search"/>
</div>
<div id="output" class="formdiv">
<input type="text" name="output"/>
</div>
</form>
<script type="text/javascript">
var company;
var jobtitle;
var keywords;
var fname;
var lname;
var notcompany;
var notjobtitle;
var notkeywords;
document.getElementById("onclick").onclick=function() {
company = document.getElementById('cmpy').value;
jobtitle = document.getElementById('jtitle').value;
keywords = document.getElementById('kwrd').value;
fname = document.getElementById('fname').value;
lname = document.getElementById('lname').value;
notcompany = document.getElementById('ncmpy').value;
notjobtitle = document.getElementById('njtitle').value;
notkeywords = document.getElementById('nkwrd').value;
alert(company + jobtitle + keywords + fname + lname + notcompany + notjobtitle + notkeywords);
}
</script>
Can you help me for changing value with javascript, but code no have id or class here is code:
<label for="flights-origin-prepop-whitelabel_en">Origin</label>
I want change "Origin" with different word.
Some examples of my code:
<button role="flights_submit" type="submit">Search</button>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text"
name="destination_name"
autocomplete="off" required=""
id="flights-destination-prepop-whitelabel_en"
placeholder="Destination"
data-label="Destination"
role="flights-destination"
data-modal-modifier="whitelabel_en"
data-placeholder-initialized="true">
<input type="hidden"
name="destination_iata"
id="flights-destination-whitelabel_en" value="">
</div>
How can change this placeholder "Destination", and label text Destination?
Thanks
You can change the origin texto doing this:
document.querySelector("label[for='flights-origin-prepop-whitelabel_en']").textContent = 'New Text';
Yes, sure, you can use querySelector with label selector including for data
console.log(document.querySelector("label[for='flights-destination-prepop-whitelabel_en']"))
<button role="flights_submit" type="submit">Search</button>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text"
name="destination_name"
autocomplete="off" required=""
id="flights-destination-prepop-whitelabel_en"
placeholder="Destination"
data-label="Destination"
role="flights-destination"
data-modal-modifier="whitelabel_en"
data-placeholder-initialized="true">
<input type="hidden"
name="destination_iata"
id="flights-destination-whitelabel_en" value="">
</div>
You can find the correct element using an "attribute selector" that looks for the for attribute and a specific value for it.
var btn = document.querySelector("button");
btn.addEventListener("click", function(){
var el = document.querySelector("[for=flights-destination-prepop-whitelabel_en]");
el.textContent = "New Value";
var input = document.getElementById("flights-destination-prepop-whitelabel_en");
input.setAttribute("placeholder","New Value");
});
<button role="flights_submit" type="button">Search</button>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text"
name="destination_name"
autocomplete="off" required=""
id="flights-destination-prepop-whitelabel_en"
placeholder="Destination"
data-label="Destination"
role="flights-destination"
data-modal-modifier="whitelabel_en"
data-placeholder-initialized="true">
<input type="hidden"
name="destination_iata"
id="flights-destination-whitelabel_en" value="">
</div>
The first step would be to set an array of the elements you want to target, which in this case is label. Then you would iterate through that array using a for loop to see if the textContent of that label is what you wanted to change. Finally, once you've 'hooked' the label you need, you can change the attributes for it as necessary. Please also note that textContent method is not cross browser compliant and so I've included a ternary script that will circumvent that thanks to this handy StackOverflow post .
HTML:
<button role="flights_submit" type="submit">Search</button>
<br/>
<br/>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text" name="destination_name" autocomplete="off" required="" id="flights-destination-prepop-whitelabel_en" placeholder="Destination" data-label="Destination" role="flights-destination" data-modal-modifier="whitelabel_en" data-placeholder-initialized="true">
<br/>
<br/>
<label for="somethingElse">OtherLabel</label>
<input type="text" id='somethingElse'>
<input type="hidden" name="destination_iata" id="somethingElse" value="">
</div>
JavaScript:
//https://stackoverflow.com/a/285608/5076162
//https://stackoverflow.com/a/13506703/5076162
var labelArray = document.getElementsByTagName('LABEL');
console.log(labelArray);
var textToChange = 'Destination';
for (var i = 0; i < labelArray.length; i++) {
var currentLabel = labelArray[i]
var text = ('innerText' in labelArray[i]) ? 'innerText' : 'textContent';
if (currentLabel[text] === 'Destination') {
var matchingInput = document.getElementById(currentLabel.htmlFor);
var newText = 'changedDestination';
var newPlaceHolder = 'changedPlaceHolder';
currentLabel[text] = newText;
matchingInput.placeholder = newPlaceHolder;
}
}
jsfiddle Example
//https://stackoverflow.com/a/285608/5076162
//https://stackoverflow.com/a/13506703/5076162
var labelArray = document.getElementsByTagName('LABEL');
console.log(labelArray);
var textToChange = 'Destination';
for (var i = 0; i < labelArray.length; i++) {
var currentLabel = labelArray[i]
var text = ('innerText' in labelArray[i]) ? 'innerText' : 'textContent';
if (currentLabel[text] === 'Destination') {
var matchingInput = document.getElementById(currentLabel.htmlFor);
var newText = 'changedDestination';
var newPlaceHolder = 'changedPlaceHolder';
currentLabel[text] = newText;
matchingInput.placeholder = newPlaceHolder;
}
}
<button role="flights_submit" type="submit">Search</button>
<br/>
<br/>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text" name="destination_name" autocomplete="off" required="" id="flights-destination-prepop-whitelabel_en" placeholder="Destination" data-label="Destination" role="flights-destination" data-modal-modifier="whitelabel_en" data-placeholder-initialized="true">
<br/>
<br/>
<label for="somethingElse">OtherLabel</label>
<input type="text" id='somethingElse'>
<input type="hidden" name="destination_iata" id="somethingElse" value="">
</div>
I'm trying to make a contact form, which should apply a class for css transitions when the input is onfocus/clicked by the user. If the user has typed name, the class from onfocus should stay there. If nothing is typed, an onblur event should remove the class and the effect.
I'm trying something like this, but I can't even make the onfocus event tricker an alert for testing my steps...
HTML:
<div>
<form class="footer-contact-form" action="">
<fieldset class="footer-form-field">
<input id="name" class="input-value" name="name" type="text" autocomplete="off" required>
<label for="name">Navn*</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="company" class="input-value" name="company" type="text" autocomplete="off">
<label for="company">Firma</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="email" class="input-value" name="email" type="email" autocomplete="off" required>
<label for="email">E-mail*</label>
</fieldset>
<fieldset class="footer-form-field-txt">
<textarea id="message" class="input-value" name="message" required></textarea>
<label for="message">Besked*</label>
</fieldset>
<input class="footer-msg-send" value="Send Besked" type="submit">
</form>
<button class="fetch-deal">Send</button>
</div>
CSS:
.input-expand {
transition: .7s;
width: 90px;
}
JS:
var inputValue = document.getElementsByClassName("input-value");
inputValue.onfocus = function() {
if (!inputValue.classList.hasClass("input-expand")) {
inputValue.addClass("input-expand");
}
// If no value is added and user does onblurr event, it should remove class .input-expand, otherwise leave class there.
}
var inputValue = document.getElementsByClassName("input-value");
var onFocus = function() { this.classList.add("input-expand");};
var onBlur = function() {if (!this.value) this.classList.remove("input-expand");};
for (var i = 0; i < inputValue.length; i++) {
inputValue[i].addEventListener('focus', onFocus, false);
inputValue[i].addEventListener('blur', onBlur, false);
}
.input-value {
transition: .7s;
width: 45px;
}
.input-expand {
transition: .7s;
width: 90px;
}
<div>
<form class="footer-contact-form" action="">
<fieldset class="footer-form-field">
<input id="name" class="input-value" name="name" type="text" autocomplete="off" required>
<label for="name">Navn*</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="company" class="input-value" name="company" type="text" autocomplete="off">
<label for="company">Firma</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="email" class="input-value" name="email" type="email" autocomplete="off" required>
<label for="email">E-mail*</label>
</fieldset>
<fieldset class="footer-form-field-txt">
<textarea id="message" class="input-value" name="message" required></textarea>
<label for="message">Besked*</label>
</fieldset>
<input class="footer-msg-send" value="Send Besked" type="submit">
</form>
<button class="fetch-deal">Send</button>
</div>
Without jQuery you could try:
var inputValue = document.getElementsByClassName("input-value");
[].forEach.call(inputValue,function(el){
el.onfocus=function() {
if (!el.classList.contains("input-expand")) {
el.className +="input-expand";
}
// If no value is added and user does onblurr event, it should remove class .input-expand, otherwise leave class there.
};
})
or as a fiddle:
https://jsfiddle.net/5v7n4je3/2/
mainly i think you problem lies in the ElementsByClassName array you have to iterate over the elements and use onFocus for every single one.
Notice the new Class is added once for every click at the moment.
I guess better solution for you to use css pseudo-classes. Use css style like below:
.input-value {
transition: .7s;
}
.input-value:focus {
width: 90px;
}
In this case you don't need to handle focus event through js and dynamically change classes of elements.
try this:
$(document).ready(function(){
$(".input-value").focus(function(){
//you focus code here
});
});
more reference: https://api.jquery.com/focus/
Using jQuery, try this :
https://api.jquery.com/focus/
$("input").focus(function() { $(this).addClass("input-expand"); });
$("input").blur(function() { $(this).val?null:$(this).removeClass("input-expand"); });
Here is the fix,
var inputValue = document.getElementsByClassName("input-value");
var onFocus = function() {
if (!this.classList.contains("input-expand")) {
this.classList.add("input-expand");
}
};
var onBlur = function() {
if (this.classList.contains("input-expand")) {
this.classList.remove("input-expand");
}
};
for (var i = 0; i < inputValue.length; i++) {
inputValue[i].addEventListener('focus', onFocus, false);
inputValue[i].addEventListener('blur', onBlur, false);
}
.input-expand {
transition: .7s;
width: 90px;
}
<div>
<form class="footer-contact-form" action="">
<fieldset class="footer-form-field">
<input id="name" class="input-value" name="name" type="text" autocomplete="off" required>
<label for="name">Navn*</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="company" class="input-value" name="company" type="text" autocomplete="off">
<label for="company">Firma</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="email" class="input-value" name="email" type="email" autocomplete="off" required>
<label for="email">E-mail*</label>
</fieldset>
<fieldset class="footer-form-field-txt">
<textarea id="message" class="input-value" name="message" required></textarea>
<label for="message">Besked*</label>
</fieldset>
<input class="footer-msg-send" value="Send Besked" type="submit">
</form>
<button class="fetch-deal">Send</button>
</div>
Try adding the script tag in the end of your body code.
Or else try and implement the solution provided below.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.my-focus-input{
border-color: red;
border-style: solid;
border-width: 1px;
height: 60px;
width: 300px;
}
.my-blur-input{
}
</style>
</head>
<body>
<input onfocus="myFocusFunction(this)" onblur="myBlurFunction(this)">
<script type="text/javascript">
function myFocusFunction(x) {
x.className = "my-focus-input";
}
function myBlurFunction(x) {
x.className = "my-blur-input";
}
</script>
</body>
</html>
Hi you just have to change yours css and js like this:
window.addEventListener("load",function(){
var inputValue = document.getElementsByClassName("input-value");
for(var i=0; i<inputValue.length; i++){
var f = inputValue[i];
f.className = "input-value input-expand";
f.addEventListener("focus", function(){this.style.maxWidth="90px";}, false);
f.addEventListener("blur", function(){if(this.value==""){this.style.maxWidth="30px";}}, false);
}
}, false);
.input-expand {
max-width:30px;
transition:max-width 0.7s ease 0s;
}
<div>
<form class="footer-contact-form" action="">
<fieldset class="footer-form-field">
<input id="name" class="input-value" name="name" type="text" autocomplete="off" required>
<label for="name">Navn*</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="company" class="input-value" name="company" type="text" autocomplete="off">
<label for="company">Firma</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="email" class="input-value" name="email" type="email" autocomplete="off" required>
<label for="email">E-mail*</label>
</fieldset>
<fieldset class="footer-form-field-txt">
<textarea id="message" class="input-value" name="message" required></textarea>
<label for="message">Besked*</label>
</fieldset>
<input class="footer-msg-send" value="Send Besked" type="submit">
</form>
<button class="fetch-deal">Send</button>
</div>
You can try something like this:
window.onload = function() {
var span1 = document.createElement("span");
span1.innerHTML = "test";
span1.className = "info";
span1.style.display = "none";
var span2 = document.createElement("span");
span2.innerHTML = "test";
span2.className = "info";
span2.style.display = "none";
var span3 = document.createElement("span");
span3.innerHTML = "test";
span3.className = "info";
span3.style.display = "none";
var username = document.getElementById("username");
username.parentNode.appendChild(span1);
var password = document.getElementById("password");
password.parentNode.appendChild(span2);
var email = document.getElementById("email");
email.parentNode.appendChild(span3);
username.onfocus = function() {
span1.className = "info";
span1.innerHTML = "infoMsg";
span1.style.display = "inline";
};
username.onblur = function() {
var alphanums = /^[a-z0-9A-Z]+$/;
if (username.value.match(alphanums)) {
span1.className = "ok";
span1.innerHTML = "Accepted";
} else {
span1.className = "error";
span1.innerHTML = "error";
}
if (username.value.length == 0) {
span1.className = "info";
span1.innerHTML = "infoMsg";
span1.style.display = "none";
}
};
password.onfocus = function() {
span2.innerHTML = "infoMsg";
span2.className = "info";
span2.style.display = "inline";
};
password.onblur = function() {
if (password.value.length < 6 && password.value.length > 0) {
span2.className = "error";
span2.innerHTML = "error";
}
if (password.value.length > 6) {
span2.className = "ok";
span2.innerHTML = "Accepted";
}
if (password.value.length == 0) {
span2.className = "info";
span2.innerHTML = "infoMsg";
span2.style.display = "none";
}
};
email.onfocus = function() {
span3.innerHTML = "infoMsg";
span3.className = "info";
span3.style.display = "inline";
};
email.onblur = function() {
var res = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
if (res.test(email.value)) {
span3.className = "ok";
span3.innerHTML = "Accepted";
} else {
span3.className = "error";
span3.innerHTML = "error";
}
if (email.value.length == 0) {
span3.className = "info";
span3.innerHTML = "infoMsg";
span3.style.display = "none";
}
};
};
All this is for this Html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Form Validation</title>
<link rel="stylesheet" href="validate.css" />
<script src="validate.js"></script>
</head>
<body>
<h1>Form Validation</h1>
<form class="signup">
<table>
<tr>
<td><label for="username">Username:</label></td>
<td><input type="text" name="username" id="username" /></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" name="password" id="password" /></td>
</tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input type="text" name="email" id="email" /></td>
</tr>
</table>
</form>
</body>
</html>