I have the following html code with a form
<form id="msg-form-nota">
<input type="hidden" name="id_nota" id="id_nota" value="${project.id}">
<label for="textfield">Calificación obtenida:</label>
<input type="text" name="nota" id="nota" class="form-control form-control-sm" value="${project.nota}" placeholder="Introducir calificación"><br>
<input type="submit" name="submit" id="submit" class="btn btn-success btn-sm" value="Añadir/modificar calificación">
</form>
and then I use the following javascript/ajax code to manage the form
$('#msg-form-nota').submit(e => {
e.preventDefault();
const postData = {
nota: $('#nota').val(),
id: $('#id_nota').val()
};
const url ='accion.php';
$.post(url, postData, (response) => {
toastr.success('añadidas!', 'Actualización ', {"hideDuration": 1500});
});
});
The problem that I detect and I don't know how to solve is that, for example, when using a while, 5 forms are created with the same name id, if I use the first form that loads me it works without problem, but if I use the rest, the form does not It works if not that all the content of the form goes to the url as if the method were a get, what can I do? Thank you
If you wanted to completely remove the ID attributes from your forms/elements you can quite easily simplify the entire code by using a FormData object with a reference to the form supplied as the single argument. The FormData object would collate the various input elements for use in the ajax request - thus negating the need to even try to identify the individual input elements explicitly.
document.querySelectorAll('[type="submit"]').forEach(input => input.addEventListener('click',e=>{
e.preventDefault();
/*
The `submit` button raised the event so the `event.target` refers to that button.
From the button we know the `form` is the parentNode - but you can use `closest`
to find the parent form.
*/
let fd = new FormData( e.target.parentNode );
fetch( 'accion.php', { method:'post', body:fd })
.then(r=>r.text())
.then(data=>{
console.log(data);
// call your success function.
toastr.success('añadidas!', 'Actualización ', {
"hideDuration": 1500
});
});
}))
<form data-id='msg-form-nota'>
<input type='hidden' name='id_nota' value='123' />
<label>
Calificación obtenida:
<input type='text' name='nota' class='form-control form-control-sm' value='Geronimo' placeholder='Introducir calificación' />
</label>
<input type='submit' class='btn btn-success btn-sm' value='Añadir/modificar calificación' />
</form>
<form data-id='msg-form-nota'>
<input type='hidden' name='id_nota' value='456' />
<label>
Calificación obtenida:
<input type='text' name='nota' class='form-control form-control-sm' value='Fred Flintsone' placeholder='Introducir calificación' />
</label>
<input type='submit' class='btn btn-success btn-sm' value='Añadir/modificar calificación' />
</form>
<form data-id='msg-form-nota'>
<input type='hidden' name='id_nota' value='789' />
<label>
Calificación obtenida:
<input type='text' name='nota' class='form-control form-control-sm' value='Spitfire' placeholder='Introducir calificación' />
</label>
<input type='submit' class='btn btn-success btn-sm' value='Añadir/modificar calificación' />
</form>
In the PHP script accion.php there will be 2 POST parameters sent by the fetch request. These two parameters have the same names as the form input elements. For instance:-
<?php
#accion.php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['id_nota'],
$_POST['nota']
)){
// ... etc do whatever
}
?>
The issue, as your question implies, is because you're repeating the same id attribute multiple times as the HTML is generated in a loop.
The best way to fix this is to use common class attributes on the elements instead. Then you can target the specific instance which from the target property of the event which is raised and passed as an argument to the event handler function. You can also use DOM traversal methods to find the related elements and retrieve their values.
Also note that I wrapped the input within the label element. This removes the need for the for and id attributes on those elements, but retains the same functionality.
$('.msg-form-nota').on('submit', e => {
e.preventDefault();
let $form = $(e.target);
const postData = {
nota: $form.find('.nota').val(),
id: $form.find('.id_nota').val()
};
console.log(postData);
/* make your AJAX request here... */
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form class="msg-form-nota">
<input type="hidden" name="id_nota" class="id_nota" value="ID_001">
<label>
Calificación obtenida:
<input type="text" name="nota" class="nota form-control form-control-sm" value="Nota_001" placeholder="Introducir calificación">
</label>
<input type="submit" name="submit" class="btn btn-success btn-sm" value="Añadir/modificar calificación">
</form>
<form class="msg-form-nota">
<input type="hidden" name="id_nota" class="id_nota" value="ID_002">
<label>
Calificación obtenida:
<input type="text" name="nota" class="nota form-control form-control-sm" value="Nota_002" placeholder="Introducir calificación">
</label>
<input type="submit" name="submit" class="btn btn-success btn-sm" value="Añadir/modificar calificación">
</form>
<form class="msg-form-nota">
<input type="hidden" name="id_nota" class="id_nota" value="ID_003">
<label>
Calificación obtenida:
<input type="text" name="nota" class="nota form-control form-control-sm" value="Nota_003" placeholder="Introducir calificación">
</label>
<input type="submit" name="submit" class="btn btn-success btn-sm" value="Añadir/modificar calificación">
</form>
Related
Trying to re-create this search url
https://www.bing.com/search?q=site:https://www.imdb.com/title+Hakunamatata
but this code keeps doing the wrong thing. I want to concatenate the URL's. Not start a second query inline
<form method="get" action="http://www.bing.com/search">
<input type="text" name="q" size="25" maxlength="255" value="Hakunamatata" />
<input type="hidden" name="q1" value="site:www.imdb.com/title" />
<input type="submit" value="Bing Search" />
</form>
What I keep getting is URL's with & in them instead of +.
Is there some kind of Javascript or something that can combine the search terms into one search?
You'll need to use JavaScript to prepend 'site:www.imdb.com/title ' to the input's value when the submit event is fired.
form.addEventListener('submit', function(){
query.value = 'site:www.imdb.com/title ' + query.value;
})
<form method="get" action="http://www.bing.com/search" id="form">
<input type="text" name="q" size="25" maxlength="255" value="Hakunamatata" id="query"/>
<input type="submit" value="Bing Search" />
</form>
So, I had a brother rebuild the script in JS since I needed some complicated formatting tweaks. This is the end result
function submitForm(elm, url, values, query) {
let baseLoc = new URL(url);
let searchParams = new URLSearchParams(baseLoc.search);
for (const key in values) {
let inputBox = elm.parentElement.querySelector(
`input[name="${values[key]}"]`
);
searchParams.set(key, inputBox.value);
}
for (const key in query) {
searchParams.set(key, query[key]);
}
let newTab = window.open(`${url}?${searchParams.toString()}`);
if (!newTab)
alert(
'Pop-up Blocker is enabled! Please add this site to your exception list.'
);
}
<form onsubmit="event.preventDefault();">
<input type="text" value="" name="inputBox" />
<input type="text" value="" name="inputBox2" /><br />
<button
onclick="submitForm(this, 'https:/\/bing.com/search/',{'q':'inputBox'},{'test':'fish','123':'lookup'});"
class="btn btn-primary btn-sm"
>
btn2
</button>
<button
onclick="submitForm(this, 'https:/\/ebay.com/sch/',{'_nkw':'inputBox2'},{'asd':'123'});"
class="btn btn-primary btn-sm"
>
btn2
</button>
</form>
Optionally, use this if you want to have a button that submits all buttons at once.
function submitAllButtons(elm) {
let allButtons = elm.parentElement.querySelectorAll('button');
console.log(allButtons);
for (const button of allButtons) {
if (elm != button) button.click();
}
}
<button onclick="submitAllButtons(this)" class="btn btn-secondary btn-sm">
ALL
</button>
Apologies if this is a straightforward question, as I am still very new to JavaScript. I have a script that validates user inputs by checking if the text-field is empty. If it is not empty, then a confirmation window prompts the user to make sure they want to continue before the form is submitted and the information uploaded.
I would like to know how I can use the code below or similar code to validate multiple forms on the same page, as currently I can only get it to work with one single form? I have tried various solutions, non of which have yet been successful. I have even tried copy/pasting the entire script and changing the relevant elements inside it.
I've stripped my alterations to the code back to where it actually works correctly. Like I said, once I try to re-use it to validate multiple forms, the code stops working correctly.
// Set up event handlers in JavaScript
document.querySelector('form').addEventListener('submit', validationCheck);
document.getElementById('updateEventTitle').addEventListener('keyup', validationCheck);
// Get your DOM references just once, not every time the function runs
let eventTitle = document.getElementById('updateEventTitle');
let btnUpdate = document.getElementById('updateBtn');
function validationCheck(event) {
if (eventTitle.value === '') {
btnUpdate.disabled = true;
} else {
btnUpdate.disabled = false;
//Confirmation window
if (event.type === 'submit') {
//Confirmation window
var r = confirm('Do you want to update this item?');
if (r == true) {
window.location.href = 'server.php';
} else {
event.preventDefault();
}
}
}
}
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTitle'>
<input type='text' id='updateEventTitle' name='myUpdateEventTitle' size='30' maxlength='40' placeholder='$row[eventName]' required>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventTitle' value='Update' id='updateBtn' disabled>
</form>
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventDate'>
<input type='text' id='updateEventDate' name='myUpdateEventDate' size='15' maxlength='10' placeholder=$eventDate required/>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventDate' value='Update' id='updateBtn' disabled>
</form>
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTime'>
<input type='text' id='updateEventTime' name='myUpdateEventTime' size='15' maxlength='5' placeholder=$eventTime required/>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventTime' value='Update' id='updateBtn' disabled>
</form>
I would like a script that is able to validate any HTML form on the page, not just the first one.
Many thanks.
We simply can took all the forms, loop through, get inputs and buttons we need for every form and set up listeners for every form, for every element.
Below is a code snippet explaining how it can be done.
// getting all forms
const elForms = [...document.querySelectorAll('form')];
// looping an array
elForms.map(elForm => {
// Get your DOM references just once, not every time the function runs
const elInput = elForm.querySelector(`input[type='text']`);
const elButton = elForm.querySelector(`input[type='submit']`);
// Set up event handlers in JavaScript
elForm.addEventListener('submit', (event) => validationCheck(event, elInput, elButton)); // passing parameters
elInput.addEventListener('keyup', (event) => validationCheck(event, elInput, elButton)); // passing parameters
});
function validationCheck(event, elInput, elButton) {
if(elInput.value==='') {
elButton.disabled = true;
} else {
elButton.disabled = false;
//Confirmation window
if(event.type === 'submit'){
//Confirmation window
var r =confirm('Do you want to update this item?');
if (r==true) {
window.location.href = 'server.php';
} else {
event.preventDefault();
}
}
}
}
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTitle'>
<input type='text' id='updateEventTitle' name='myUpdateEventTitle' size='30' maxlength='40' placeholder='$row[eventName]' required>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventTitle' value='Update' id='updateBtn' disabled>
</form>
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventDate'>
<input type='text' id='updateEventDate' name='myUpdateEventDate' size='15' maxlength='10' placeholder=$eventDate required/>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventDate' value='Update' id='updateBtn' disabled>
</form>
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTime'>
<input type='text' id='updateEventTime' name='myUpdateEventTime' size='15' maxlength='5' placeholder=$eventTime required/>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventTime' value='Update' id='updateBtn' disabled>
</form>
After answer
There are duplicating id in your example
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTitle'>
<input type='text' id='updateEventTitle'
This is not valid and can cause problems in future. id should be unique.
How can we get values of form elements inside fieldset?
<fieldset id='myFieldset'>
<label for='Resp'>Responsibilities</label><input id='input' type='text' size='55'>
<button type='button' class='btn-sm' style='width:50px;margin:2px' id='addItem'>Add</button>
<button type='button' class='btn-sm' style='width:50px;margin:2px' id='clear'>Clear</button>
<button type='button' class='btn-sm' style='width:50px;margin:2px' id='edit'>Edit</button>
<ul id='output' style='display:none'></ul>
<br class='clear' />
<textarea disabled name='Resp' id='Resp' cols='75' rows='5' required></textarea>
</fieldset>
I have some more fields similar to this in a page. So I need to get values from input form and also from specific fieldset. How can I do it in jQuery?
If you are using id attributes:
<input type="text" id="txtData" name="txtData" />
JQuery:
$("#myFieldset #txtData").val();
If you are using class attributes.
<input type="text" class="txtEmail" />
Jquery
$("#myFieldset .txtEmail").val();
You are able to get all ids value from fieldset as below:
Html
<fieldset id='myFieldset'>
<input type="text" id="txtData" name="txtData" />
<input type="text" class="txtEmail" />
<input type="button" class="btntest" />
</fieldset>
jQuery
$(".btntest").click(function () {
$("#myFieldset input[type != button]").each(function(key,value){
alert($(this).val());
});
});
So this thing will give you all inputs not then type = button value.
Here you go with the solution https://jsfiddle.net/f3xwzap9/
var data = {};
$('#addItem').click(function(){
$('fieldset#myFieldset > input, textarea').each(function(){
data[$(this).attr('id')] = $(this).val();
});
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id='myFieldset'>
<label for='Resp'>Responsibilities</label><input id='input' type='text' size='55'>
<button type='button' class='btn-sm' style='width:50px;margin:2px' id='addItem'>Add</button>
<button type='button' class='btn-sm' style='width:50px;margin:2px' id='clear'>Clear</button>
<button type='button' class='btn-sm' style='width:50px;margin:2px' id='edit'>Edit</button>
<ul id='output' style='display:none'></ul>
<br class='clear' />
<textarea name='Resp' id='Resp' cols='75' rows='5' required></textarea>
</fieldset>
I have attached an event in Add button.
I'm looping through all the input & textarea inside the fieldset & collecting the data.
Data is in JSON format id as key and value is value.
Since I'm looping through all the input & textarea, it will help you to collect all the child (input & textarea) data, rather than collecting the data specifically.
Try this:
var inputVal = $('#myFieldset #input').val();
var textAreaVal = $('#myFieldset #Resp').val();
$('#myFieldset').find('input').val()
I have a problem with jquery ajax multi form.
every execution is always part of the form at the top, to form the other does not work.
can help me.
this Source Code
<form id="form_action" action="http://www.dom.dom/act/">
<input type="text" name="nama" value="" />
<button type="submit" >Save</buton>
</form>
<form id="form_action" action="http://www.dom.dom/act/">
<input type="text" name="nama" value="" />
<button type="submit" >Save</buton>
</form>
<form id="form_action" action="http://www.dom.dom/act/">
<input type="text" name="nama" value="" />
<button type="submit" >Save</buton>
</form>
<form id="form_action" action="http://www.dom.dom/act/">
<input type="text" name="nama" value="" />
<button type="submit" >Save</buton>
</form>
jquery ajax nya :
$("#form_action").on('submit', function(e){
e.preventDefault();
var link = $(this).attr("action");
var data = $(this).serialize();
$.ajajx({
url:link,
data:data,
type:"POST",
typeData:'html',
cache:false,
success: function(data){
//// bla bla //
}
});
return false;
});
How to use this jquery for multi form..?
When you use an id selector ($('#some-id')) you get only the first element that matches your selector, not an array as you get with other selectors.
Also, it seems that they're all the same form.. What are you trying to achieve? Maybe you can use the same form and just change action attribute or some input in the form.
Another thing, as #dave mentioned in the comments, there's no $.ajajx function in jQuery :-)
I have one form on a page with no submit button:
<form id='voteForm' action='xyz' method='post'>
<fieldset>
<input type="hidden" id="task_id" value="{$feature_details['task_id']}" />
<input type="hidden" id="vote_id" value="{$vote['vote_id']}" />
<input type="hidden" id="vote_type" value="{$vote['vote_type']}" />
<input type="hidden" id="vote_rating" value="{$vote['vote_rating']}" />
<input id="btn-update-vote" class="btn btn-sm btn-primary" type='button' disabled="disabled" value="{L('SubmitVote')}">
</fieldset>
</form>
I cannot get jQuery to trap a click event on the 'SubmitVote' button
neither of these appear to work:
$('#btn_update_vote').click(function() {
console.log('Click: #btn_update_vote');
})
$('form#voteForm').on('click', '#btn_update_vote', function() {
console.log('Click: #btn_add_comment');
})
I do not understand what can cause this!
Any help appreciated!
BTW: I CAN set the disabled attribute on the button using jQuery and on 'documentReady' I log the button to the console:
[Log] [ (tracker, line 446)
<input id="btn-update-vote" class="btn btn-sm btn-primary" type="button" disabled="disabled" value="Cast Your Vote">
]
Your button attr disabled="disabled" make it unclickable, even inline onclick listen.
<input id="btn-update-vote"
$('#btn_update_vote').click( //...
You declared your id with dashes (-), not underscores (_), so you need
$('#btn-update-vote').click(
Also #Richer is correct