first post here, i'm trying to write a code following a tutrial, its a to do list and i wrote a function that takes the content of a text type input and adds it to a list, im testing the code using an alert inside the function but it doenst work and no alerts are shown, here's the code. Thanks in advance
let elements = [];
function addElements(){
if (document.querySelector("#task").nodeValue.trim() != ""){
elements.push(document.querySelector("#task").nodeValue.trim())
alert(elements);
}
}
<body>
<div class="container">
<div id="todoList"></div>
<form action="#" id="todoForm">
<label for="task">Task: </label>
<input type="text" name="task" id="task" autofocus>
<button class="addBtn">
<img src="https://upload-icon.s3.us-east-2.amazonaws.com/uploads/icons/png/20340289291547546467-64.png" alt="">
</button>
<!--<input type="submit" id="submit" value="Add To-Do">-->
</form>
</div>
<script src="../todo_list/apps.js"></script>
</body>
So your problem was you didn't call addElements() on your button.
and instead of using nodeValue just use value instead.
this is working code
let elements = [];
function addElements(){
console.log(document.querySelector("#task").value)
if (document.querySelector("#task").value.trim() != ""){
elements.push(document.querySelector("#task").value.trim())
alert(elements);
}
}
<body>
<div class="container">
<div id="todoList"></div>
<form action="#" id="todoForm">
<label for="task">Task: </label>
<input type="text" name="task" id="task" autofocus>
<button class="addBtn" onclick="addElements()">
<img src="https://upload-icon.s3.us-east-2.amazonaws.com/uploads/icons/png/20340289291547546467-64.png" alt="">
</button>
<!--<input type="submit" id="submit" value="Add To-Do">-->
</form>
</div>
</body>
First you need to stop the html form submit with
<form action="#" id="todoForm" onsubmit="return false;">
Then you need to bind click function to your button, so that when button clicked your addElements function will be triggered
<button class="addBtn" onclick="addElements()">
Finally you need to get the input value with
document.getElementById('task').value;
Complete Code Sample
let elements = [];
function addElements() {
var task = document.getElementById('task').value;
if (task.trim() != "") {
elements.push(task);
alert(elements)
}
}
<body>
<div class="container">
<div id="todoList"></div>
<form action="#" id="todoForm" onsubmit="return false;">
<label for="task">Task: </label>
<input type="text" name="task" id="task" autofocus>
<button class="addBtn" onclick="addElements()">
<img src="https://upload-icon.s3.us-east-2.amazonaws.com/uploads/icons/png/20340289291547546467-64.png" alt="">
</button>
</form>
</div>
</body>
Related
I'm doing a project and I don't understand the front end well.
I have this html page:
<form class="form-group" action="/create" method="post" enctype="multipart/form-data">
<div class="title">
<h1>Cadastre seu produto</h1>
</div>
<div class="single-input">
<input class="form-control" placeholder="nome do produto" type="text" id="nome_produto" name="nome_produto">
</div>
<div class="single-input">
<input class="form-control" placeholder="quantidade em estoque" type="number" id="quantidade" name="quantidade">
</div>
<div class="single-input">
<input class="form-control" placeholder="preco do produto" type="number" id="preco_produto" name="preco_produto">
</div>
<button onclick="loadPage()" id="button" type="submit" class="btn btn btn-danger">ENVIAR</button>
</form>
I want that when I click on the SUBMIT button, I am redirected to another page, I want to do this using Javascript.
I tried to do this:
<script type="text/javascript">
function loadPage(){
window.location("http://localhost:8080/list")
}
but it's not working, every time I click on the button I'm redirected to a blank page
Any solution ?
Window.location is a property not a function. So it should be
window.location = "http://localhost:8080/list";
More details here: https://developer.mozilla.org/en-US/docs/Web/API/Window/location
I inserted a form on a html page, which contains several fields the user is supposed to fill ("name", "surname", a textarea, and so on); I then added a button and assigned the id Click to it:
<input type="button" name="button" value="Click" id="cliccami">
I linked the html page to a JQuery file.
By using JQuery I want to add a function clearAll which clears all the fields in the form when the user clicks on the button. I want to use another function main which calls the function clearAll when the button is clicked, as in the following:
function main() {
$("form").on("button", clearAll);
}
How can I write the function clearAll (to empty the fields in the form) by using JQuery?
Inside the function you can target the closest() form of this element to find all the elements to clear them like the following way:
function main() {
$("form").on("click", "#cliccami", clearAll);
}
function clearAll() {
$(this).closest("form").find("input[type=text], textarea").val("");
}
function main() {
$("form").on("click", "#cliccami", clearAll);
}
main();
function clearAll() {
$(this).closest("form").find("input[type=text], textarea").val("");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<form>
<div>
<label>First Name:</label>
<input type="text" id="first-name">
</div>
<div>
<label>Last Name:</label>
<input type="text" id="last-name">
</div>
<div>
<label>Comments:</label>
<textarea id="comments"></textarea>
</div>
<input type="button" name="button" value="Click" id="cliccami">
</form>
Use jQuery's .val() function to set the value of a input element. Check the snippet for an example:
function clearAll() {
$(":input[type=text]").val("");
}
function main() {
$("#cliccami").on("click", clearAll);
}
main();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="test">
<input type="button" name="button" value="Click" id="cliccami">
You can bind your function using the onclick attribute. And use reset method to reset the entire form this way.
function main(){
// reset form
$('#my-form')[0].reset();
// do whatever you want
alert('Form cleared!');
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<div class="container">
<h2>Form</h2>
<form id="my-form">
<div class="form-group">
<label for="first-name">First Name:</label>
<input type="text" class="form-control" id="first-name">
</div>
<div class="form-group">
<label for="last-name">Last Name:</label>
<input type="text" class="form-control" id="last-name">
</div>
<div class="form-group">
<label for="comments">Comments:</label>
<textarea class="form-control" id="comments"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" onclick="main()" class="btn btn-default">Clear All</button>
</form>
</div>
Try this
<form id="form1" action="">
<input type="text">
<input type="text">
<textarea name="" id="" cols="30" rows="10"></textarea>
<input type="button" name="button" value="Click" id="cliccami">
</form>
function clearAll() {
$('#form1 input, #form1 textarea, #form1 select').each(function() {
$(this).val('');
});
}
$("#cliccami").on('click',function(){
clearAll();
});
$('#clearit').click(function(){
$(":input[type=text]").val("");
setTimeout(function(){ afteremptyfield(); }, 1000);
})
function afteremptyfield(){
alert("Function trigged after clearing fields")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="test">
<input type="button" name="button" value="Clear and trigger a function" id="clearit">
This is how it could be done....
I have a Multi forms that contain some inputs
<form class="form" role="form" onsubmit="completeSave()">
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="submit" id="{{$media->id}}" class="btn blue">ارایه</button>
</div>
</form>
<form class="form" role="form" onsubmit="completeSave()">
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="submit" id="{{$media->id}}" class="btn blue">ارایه</button>
</div>
</form>
I want to get value of inputs on submitting form I tried this code but it didnt worked
function completeSave() {
event.preventDefault();
var thisForm = $(this);
console.log(thisForm.find('input[name="name"]').val())
}
it returns undefined in console
you are using jQuery for this case.
You need to import your jQuery then use below function
jQuery can be found at
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
function completeSave(e) {
event.preventDefault();
var thisForm = $(e).find("[name=name]");
console.log(thisForm.val());
}
FORM
<form class="form" role="form" onsubmit="completeSave(this)"> <!-- add this -->
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="submit" id="{{$media->id}}" class="btn blue">ارایه</button>
</div>
</form>
use this java script code
function completeSave() {
event.preventDefault();
console.log($("#name").val());
}
but add an id on text input as -
<input type="text" class="form-control" name="name" id="name"
value="{{$media->name}}">
HTML forms
<form class="form" role="form" id="form1">
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="button" id="{{$media->id}}" class="btn blue" onclick="completeSave("form1");">ارایه</button>
</div>
Scripts
function completeSave(formId) {
console.log($("#"+formId+' input[name="name"]').val())
}
Hope it helps :)
fist i assume you are using jquery
solution 1
the keyword this only evaluates to the form if the completeSave function
is called via jquery's submit event, so for this solution, you don't need the completeSave function on the form's HTML tag
$('form').submit(function(event) {
event.preventDefault();
var thisForm = $(event.target);
console.log(thisForm.find('input[name="name"]').val())
})
solution 2
you should pass the event argument to the completeSave function located on onsubmit attribute of form's HTML tag
ex: <form onsubmint="completeSave(event)">
since the this keyword doesn't evaluate to the form, you gotta select it manually
function completeSave(event) {
event.preventDefault();
var thisForm = $(event.target);
console.log(thisForm.find('input[name="name"]').val())
}
and the input[name="name"] will be the one whos form is submited
Please try this one:
For sure you should add unique id to your forms
<form class="form" role="form" id="form1" onsubmit="completeSave(form1)">
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="submit" id="{{$media->id}}" class="btn blue">ارایه</button>
</div>
</form>
<form class="form" role="form" id="form2" onsubmit="completeSave(form2)">
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="submit" id="{{$media->id}}" class="btn blue">ارایه</button>
</div>
</form>
and your javascript code could look like this:
function completeSave(form) {
event.preventDefault();
var input = $("#" + form + " :text");
console.log(input.val());
}
I am creating search form, when user click search icon, i need to show textbox, once i entered content, and again clicked same search icon, it needs to display search results. Below is the code i used.
HTML & Javascript
<div class="search_right">
<div class="search-top-container">
<div class="search-top"></div>
<div class="search-form">
<div class="search-form-border"></div>
<div class="search-top-title"><span class="icon"></span>Search</div>
<form id="search_mini_form" action="%%GLOBAL_ShopPath%%/search.php" method="get">
<div class="form-search">
<input id="search" type="text" name="q" value="" class="input-text" style="display:none;" autocomplete="off">
<button type="submit" title="Search" id="but" onclick="tog_input();" >
</button>
</div>
<div id="search_autocomplete" class="search-autocomplete" style="display: none;"></div>
<script type="text/javascript">
function tog_input(){
if(jQuery("#search").is(':visible'))
{
if(jQuery("#search").val()!=''){ jQuery("#search_mini_form").submit();
}else{
jQuery("#search").animate({ width: 'hide' });
}
}
else
{
jQuery("#search").animate({ width: 'show' });
}
}
</script>
</form>
</div>
<div class="clear"></div>
</div>
Right now issue is, when i clicked search icon, it showing search page instead of textbox, any assistance would be appreciated.
Change the inline code from:
<button type="submit" title="Search" id="but" onclick="tog_input();">Submit</button>
To:
<button type="submit" title="Search" id="but" onclick="tog_input(this, event);">Submit</button>
Avoid this line:
jQuery("#search_mini_form").submit();
Prevent the form submission only when needed.
So:
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div class="search_right">
<div class="search-top-container">
<div class="search-top"></div>
<div class="search-form">
<div class="search-form-border"></div>
<div class="search-top-title"><span class="icon"></span>Search</div>
<form id="search_mini_form" action="%%GLOBAL_ShopPath%%/search.php" method="get">
<div class="form-search">
<input id="search" type="text" name="q" value="" class="input-text" style="display:none;"
autocomplete="off">
<button type="submit" title="Search" id="but" onclick="tog_input(this, event);">Submit
</button>
</div>
<div id="search_autocomplete" class="search-autocomplete" style="display: none;"></div>
<script type="text/javascript">
function tog_input(obj, e) {
if (jQuery("#search").is(':visible')) {
if (jQuery("#search").val() == '') {
jQuery("#search").animate({width: 'hide'});
e.preventDefault();
}
}
else {
e.preventDefault();
jQuery("#search").animate({width: 'show'});
}
}
</script>
</form>
</div>
<div class="clear"></div>
</div>
</div>
I'd suggest that it is because your button type is submit. If you change it to button type = "button" then it should work, although you may need another button to submit your form.
You need to prevent default behaviour of submit button else it will end up in action page. To achieve it you need to do as -
function tog_input(e){
e.preventDefault();// prevents default action
... other code
}
I have 4 forms in my html, and required that form's id which submitted. But every time constantly first form's id comes in output.
My HTML is:
<form name="form" id="filterHeadByFamNum" class="form-horizontal" role="form">
<div class="form-group">
<label>Family Number</label> <input type="text" name="familyNumber" placeholder="Family Number" class="form-control">
</div>
<button type="button" class="btn btn-primary" onclick="filterByFamNum();return false;">Submit</button>
</form>
<form name="form" id="filterHeadByMemName" class="form-horizontal" role="form">
<div class="form-group">
<label>Head Name</label> <input type="text" name="head" placeholder="Head Name" class="form-control">
</div>
<button type="button" class="btn btn-primary" id="head" onclick="filterByMemName();return false;">Submit</button>
</form>
<form name="form" id="filterMemberByPhone" class="form-horizontal" role="form">
<div class="form-group">
<label>Phone Number</label> <input type="text" name="phone" placeholder="Phone Number" class="form-control">
</div>
<button type="button" class="btn btn-primary" onclick="filterByPhone();return false;">Submit</button>
</form>
<form name="form" id="filterMemberByCNIC" class="form-horizontal" role="form">
<div class="form-group">
<label>CNIC</label> <input type="text" name="cnic" placeholder="CNIC" class="form-control">
</div>
<button type="button" class="btn btn-primary" onclick="filterByCNIC();return false;">Submit</button>
</form>
and my js is
function filterByFamNum(){
var name = $(this.form).attr('id');
console.log(name);
}
function filterByMemName(){
var name = $(this.form).attr('id');
console.log(name);
}
function filterByPhone(){
var name = $(this.form).attr('id');
console.log(name);
}
function filterByCNIC(){
var name = $(this.form).attr('id');
console.log(name);
}
Ouptut of every form submit is constantly filterHeadByFamNum
Rather than adding event listeners to the buttons, just listen for the submit event on the form:
$('form').on('submit', function () {
var id = this.id;
console.log(id);
});
..or without jQuery:
Array.prototype.forEach.call(document.querySelectorAll('form'), function (el) {
el.addEventListener('submit', function () {
var id = el.id;
console.log(id);
});
});
I would use #JoshCrozier's solution for this problem but just for the sake of completion and/or if you're adamant about using your solution instead. Here it is:
jsbin DEMO -> http://jsbin.com/yiteludomu/2
Add this as a parameter in each of your javascript functions to send the button you're clicking.
<button type="button" class="btn btn-primary" onclick="filterByFamNum(this);return false;">Submit</button>
here is how you handle button click .. observe btn which is the clicked button.
function filterByFamNum(btn){
var name = $(btn).parent('form').attr('id');
alert(name);
}
var submittedForms = [];
$('form').on('submit', function () {
submittedForms.push(this.id);
});
submittedForms array will hold the ids of all the submitted form.