How to get form's id, only which submitted - javascript

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.

Related

unable to display a list with alert function

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>

value of a textarea element

I want to use value of a textarea element, but I am not able to get it
function postComment(element) {
const content = element.previousSibling.value;
console.log(content);
}
<form action="" class="comment-editor">
<div class="form-group">
<textarea class="form-control" name="" id="someid" rows="4"></textarea>
<button type="button" class="btn btn-primary my-2" onClick="postComment(this)">Comment</button>
</div>
</form>
It gives undefined as output
Can you try the below code
function postComment(element) {
const content = element.parentNode.firstElementChild.value
console.log(content);
return false;
}
<form action="" class="comment-editor">
<div class="form-group">
<textarea class="form-control" name="" id="someid" rows="4"></textarea>
<button type="button" class="btn btn-primary my-2" onClick="return postComment(this)">Comment</button>
</div>
</form>
function postComment(element) {
const content = element.previousElementSibling.value;
console.log(content);
}
<form action="" class="comment-editor">
<div class="form-group">
<textarea class="form-control" name="" id="someid" rows="4"></textarea>
<button type="button" class="btn btn-primary my-2" onClick="postComment(this)">Comment</button>
</div>
</form>
Your problem is that you use previousSibling when it should be previousElementSibling.
Since you already have an ID for the <input> field, i would have used the following instead:
function postComment() {
const content = document.getElementByID("someid").value;
console.log(content);
}
And no need for the parameter here:
onClick="postComment();"
You can fetch value by this modification in your code
const content = document.querySelector("#someid").value;

How can I tell the browser to empty a field by using JQuery and then call the function?

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....

send input data with onsubmit method

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 use onclick function on submit but form action is not responding

here is function
function myFunction(button) {
var oldValue = button.value;
button.setAttribute('disabled', true);
button.value = '...processing...';
setTimeout(function () {
button.value = oldValue;
button.removeAttribute('disabled');
}, 3000)
}
and here is form-
<form id="addform" action="index.php/adminuser/insert_state" method="post">
<div class="form-group">
Contact Number
<input type="text" required="" name="contact" class="form-control">
</div>
<div></div>
<div class="form-group">
<button class="btn btn-info" type="submit" id="submit" onclick="myFunction(this)">Submit </button>
</div>
</form>
but form action is not working...please help me how to use disabled button and form action in a single form..
Thanks for help in advance.

Categories