How to add a value to submitted form using JS - javascript

I have the following html code:
<form>
<input autofocus type="text" name="rnum" id="rnum" class="input-field" placeholder="Number of rows in a page">
</form>
<script type="text/javascript">
document.getElementById('rnum')
.addEventListener('keyup', function(event) {
if (event.code === 'Enter') {
.append(window.location.search)
.toString();
event.preventDefault();
document.querySelector('form').submit();
}
});</script>
I have a search data in window.location that I want to add to the submitted value of the form. For instance, the url is:
http://127.0.0.1:5000/result?searchbox=cor
and the value of the form is rnum=10 that I want to combine and make:
http://127.0.0.1:5000/result?searchbox=cor&rnum=10
update 1:
As #Yasir suggested, I replaced the code,
<form style="float: right;">
<input autofocus type="text" name="rnum" id="rnum" class="input-field" placeholder="Number of rows in a page">
</form>
<script type="text/javascript">
document.getElementById('rnum')
.addEventListener('keyup', function(event) {
if (event.code === 'Enter') {
let child = document.createElement('input');
child.name = "searchBox";
child.value = window.location.search.toString();
event.preventDefault();
var form = document.querySelector('form');
form.appendChild(child);
form.submit()
}
});</script>
But still the result is like: http://127.0.0.1:5000/result?rnum=10 for 10 in form.

well, you can create an input node with the desired value within the form and then submit it.
<form>
<input autofocus type="text" name="rnum" id="rnum" class="input-field" placeholder="Number of rows in a page">
</form>
<script type="text/javascript">
document.getElementById('rnum')
.addEventListener('keyup', function(event) {
if (event.code === 'Enter') {
let child = document.createElement('input');
child.name = "searchBox";
child.value = window.location.search.toString();
event.preventDefault();
var form = document.querySelector('form');
form.appendChild(child);
form.submit()
}
});</script>
and if you are looking for updating the page url appending some value from form input
<script type="text/javascript">
document.getElementById('rnum')
.addEventListener('keyup', function(event) {
event.preventDefault();
if (event.code === 'Enter') {
let input = document.getElementById("rnum");
window.location.search += "&rnum=" +input.value;
}
});</script>

I think you have a syntax error in this part
if (event.code === 'Enter') {
.append(window.location.search)
.toString();// this is an error since we are not appending the string anywhere
event.preventDefault();
document.querySelector('form').submit();
}

Related

Check textarea is empty with queryselector

I am trying to check if "textarea" is empty and if thats the case trigers a validation function. so far It works if I use an input but textarea doesnt have a value and queryselector doesnt get a value of it.
Javascript
const commentValidation = document.querySelectorAll("textarea").value;
const checkComment = () =>{
let valid = false;
const comment = commentValidation;
if(!isRequired(comment)){
showError(commentValidation, "Comment cannot be blank");
}else if(!isCommentValid(comment)){
showError(commentValidation,"comment is not valid")
}else{
showSuccess(commentValidation);
valid = true;
}
return valid;
};
const isCommentValid = (comment) =>{
const re = /[a-zA-Z]/;
return re.test(comment);
};
const showSuccess = (input) =>{
const formField = input.parentElement;
formField.classList.remove('error');
formField.classList.add('success');
const error = formField.querySelector('small');
error.textContent = '';
}
form.addEventListener('submit', function (e){
e.preventDefault();
let isCommentValid = checkComment(),
let isCommentValid
if (isFormValid){
}
});
HTML
<div class ="form-field">
<label for="comment">Send a comment</label>
<textarea id="commentID" name="comment" autocomplete="off"></textarea>
<small></small>
</div>
Any ideas how to use queryselector and check if user didnt put a comment.
You don't need a javascript validation. Just add required to the textarea, and the browser will handle everything for you.
<form onsubmit="return false">
<div class="form-field">
<label for="comment">Send a comment</label>
<textarea id="commentID" name="comment" autocomplete="off" required></textarea>
<small></small>
</div>
<button type="submit">Submit</button>
</form>
the submit property is a property of a button or form. but you are using a div.
change html
<form class ="form-field" id="form-div">
<label for="comment">Send a comment</label>
<textarea id="commentID" name="comment" autocomplete="off"></textarea>
<small></small>
</form>
here we convert div tag to form
add javascript
const form = document.getElementById("form-div");
and let's put a trigger
in javascript
form.addEventListener('keyup', function (e){
e.preventDefault();
if (e.key === 'Enter' || e.keyCode === 13) {
form.submit();
}
});
Press the enter key and the form will be sent.
Working Demo : Demo

My JavaScript doesn't run when the html is in a form

HTML
I have some simple html input here and I would like to put it in a POST form
<form method="POST">
{% csrf_token %}
<input type="text" id="myTextInputID" placeholder=" Your amazon URL">
</form>
JAVASCRIPT
function search(){
var inputValue = document.getElementById("myTextInputID").value;
}
document.getElementById("myTextInputID").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
var input = document.getElementById("myTextInputID").value;
document.getElementById(search());
var error = document.getElementById("error")
if (input.includes("https://www.amazon.co.uk/")){
error.style.display = "none";
}else{
error.style.display = "block";
setTimeout(function(){error.style.display = "none";} ,2000)
}
}
});
function togglePopup(){
document.getElementById("popupe-1").classList.toggle("active");
}
And I have my if function here when I don't have my user input as a post method it works perfectly fine, but when I add the post method the page just reloads each time and doesn't run my javascript function
It because when user presses Enter, it triggers the form submit action, and it will reload the page.
To prevent form submit action to be triggers, add onkeydown="return event.key != 'Enter';" to your form.
function search(){
var inputValue = document.getElementById("myTextInputID").value;
}
document.getElementById("myTextInputID").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
var input = document.getElementById("myTextInputID").value;
document.getElementById(search());
var error = document.getElementById("error")
if (input.includes("https://www.amazon.co.uk/")){
error.style.display = "none";
}else{
error.style.display = "block";
setTimeout(function(){error.style.display = "none";} ,2000)
}
}
});
function togglePopup(){
document.getElementById("popupe-1").classList.toggle("active");
}
<form action="https://www.google.com" method="POST" onkeydown="return event.key != 'Enter';">
<input type="text" id="myTextInputID" value="https://www.amazon.co.uk/" />
</form>
<div id="popupe-1">Helloworld</div>
<div id="error">I'm a error</div>

tabindex navigation using "enter key" not working in dropdown

I have used below code for tabindex navigation using "enter key" in html form.It works fine as per my requirement,but this code is not working in dropdown.Please check below code and advise how to do this..
document.addEventListener('keydown', function (event) {
if (event.keyCode === 13 && event.target.nodeName === 'INPUT') {
var form = event.target.form;
var index = Array.prototype.indexOf.call(form, event.target);
form.elements[index + 1].focus();
event.preventDefault();
}
});
You just need to change your if statement to include the select node as example below.
document.addEventListener('keydown', function (event) {
if (event.keyCode === 13 && (event.target.nodeName === 'INPUT' || event.target.nodeName === 'SELECT')) {
var form = event.target.form;
var index = Array.prototype.indexOf.call(form, event.target);
event.preventDefault();
}
});
<form>
<input type="text">
<input type="checkbox">
<select>
<option>123</option>
</select>
<input type="radio">
</form>

How to get the search to work when the user presses enter

This is the button Iv`e created and search bar that has a function to go to a page when a user clicks search tab but I need it to work when the user presses enter as well.
This is the search bar and button
<input type="text" method="get" class="form-control" id="search" placeholder="Search" value="">
<button type="button" id="go" class="btn btn-default" onclick="sendToPage();">Search</button>
This is the function
function sendToPage(){
var input = document.getElementById("search").value;
//Check to see if the user has entered apple/iphone;
if (input === "apple"){
//location.href="apple.html";
location.replace("apple.html");
return false;
}
else if (input === "iphone"){
location.replace("apple.html");
return false;
}
}
Putting a form around the input should give you the result you're looking for. Then just add an "onsubmit" to the form that calls your sendToPage(); function.
You can add a keyup and check its event.keyCode. If the key code is 13, it means the user clicked enter while on the input text.
Something like this:
document.getElementById("search")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode == 13) {
if (input === "apple")
location.replace("apple.html");
else if (input === "iphone")
location.replace("apple.html");
}
return false;
});
Or using your function sendToPage():
document.getElementById("search")
.addEventListener("keyup", function(event) {
event.preventDefault();
sendToPage();
return false;
});
It seems the id of your input field is 'search' so you can try this:
note that the keycode of enter is 13. so we can compare the input codes with 13. if its true then do the search.
$('#search').keydown(function(event) {
if (event.keyCode == 13) {
var input = $(this).val();
if (input === "apple"){
//location.href="apple.html";
location.replace("apple.html");
return false;
}
else if (input === "iphone"){
location.replace("apple.html");
return false;
}
return false;
}
});
});
This is the button
<!-This is the button -->
<div id="search-bar">
<div class="form-group">
<input type="text" method="get" class="form-control" id="search" placeholder="Search" value="">
<button type="button" id="go" class="btn btn-default" onclick="sendToPage();" onChange="aliasonclick">Search</button>
</div>
</div>

OnBlur Validation Requires Onsubmit Button to Be Clicked Twice in Pure Javascript

I have a form which validates password null/blank or not using onblur. And I use a submit button to submit the form. However the submit button needs to be clicked twice before to work. It does not work on the first click after something has been filled in the password box. Below is the code.
With respect to Jquery, I require solution in pure Javascript.
I have tried onkeyup, but that is not a good solution as it will put strain on system, and server (for ajax).
<!DOCTYPE html>
<html>
<body>
<script>
var error_user_password = false;
function checkpw(){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall() {
checkpw()
if(error_user_password == false) {
return false;
} else {
return true
}
}
</script>
</body>
<form id="joinform" method="post" name="joinform" action="#hello" onsubmit="return submitall()" >
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password" onblur="checkpw()" />
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
</html>
OnBlur Validation Requires Onsubmit Button to Be Clicked Twice in Pure Javascript
This happens because the blur event is captured from the onblur event handler and not bubbled to the form submit button.
A full javaScript solution is based on:
addEventListener
activeElement: inside the blur event I check after 10 milliseconds if the submit button get the focus.
My snippet:
var error_user_password = false;
function checkpw(ele, e){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_password == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) {
document.getElementById('user_password').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>

Categories