I have a large form that I want to monitor for changes. I found example code for that in this post. When I run the code as posted, it works fine. But my form is using Ajax and it doesn't work for some reason. Here's my jsfiddle. I added a second monitor near the bottom but it isn't working either.
When the monitoring code is in the doc ready function, even the first "hello" update doesn't work. But this may be something to do with jsfiddle since I can get past that point locally. But even then, the origForm data is not seen more than once because, I think, the doc ready function is only called the one time when Ajax loads it.
Is there a way to monitor all of the fields when using Ajax?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="saved_form"></div>
<div id="changed"></div>
<div id="showform"></div>
<script>
$(document).ready(function() {
ShowForm();
$("#saved_form").text("hello");
var $form = $("form"),
origForm = $form.serialize();
$("#saved_form").text(origForm);
$("form :input").on("change input", function() {
$("#changed").text("A change was made");
});
});
function ShowForm () {
$.ajax({
url: 'ajax3.php',
success: function(data) {
$("#showform").html(`
<form>
<div>
<textarea name="description" cols="30" rows="3"></textarea>
</div>
<div>Username: <input type="text" name="username" /></div>
<div>
Type:
<select name="type">
<option value="1">Option 1</option>
<option value="2" selected>Option 2</option>
<option value="3">Option 3</option>
</select>
</div>
<div>
Status: <input type="checkbox" name="status" value="1" /> 1
<input type="checkbox" name="status" value="2" /> 2
</div>
</form>
`);
}
});
};
var $form2 = $("form"),
origForm2 = $form2.serialize();
$("#saved_form").text(origForm2);
$("form :input").on("change input", function() {
$("#changed").text("A change was made");
});
</script>
You are dynamically adding the form to your page. The selector will not pick up the change event. Also the event and selector in the on method are defined properly. more information about the on method can be found here http://api.jquery.com/on/
Try this:
$(document).on("change", "input, textarea", function() {
$("#changed").text("A change was made");
});
You can use .promise() after using .html() to render your form. This callback is launched right after form has been populated. Then you can use $("#showform form :input") to monitor events just on this eactly form. It costs less in performance than doing with $(document).on(...)
In your code:
function ShowForm () {
$.ajax({
url: 'test',
success: function(data) {
$("#showform").html(`
// <--- All your previous html -->
`).promise().done(function(){
// <--- Execute your monitor after rendering new form -->
$("#showform form :input").on("change input", function() { $("#changed").text("A change was made");
});
});
}
});
};
Look at the updated jsfiddle
To know more about .promise() here-jquery-promises
Related
I have a form, and when the submit button is clicked, it sends an AJAX request. This works on the button click by:
$(#form).submit(function(event) {
event.preventDefault();
$.ajax({
// ...
})
});
The form data is passed to the URL in the ajax command using data.
Is there a way this form can be submitted and the same AJAX function can run on a dropdown change javascript/jQuery event? The dropdown menu is in the same form.
I have it so that when the AJAX returns successfully, it adds the HTML to populate a div with a table so this needs to be written once.
Short answer: "Yes". You can call the "submit" method of the form from anywhere you like. For example:
$("#someDropdown").change(function() { $("#form").submit(); });
Demo:
$(function() {
$("#someDropdown").change(function() {
$("#form").submit();
});
$("#form").submit(function(event) {
event.preventDefault();
console.log($(this).serialize());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="someDropdown">
<option>Option 1</option>
<option>Option 2</option>
</select>
<hr>
<form id="form">
<input type="text" name="text1" />
<button type="submit">Submit</button>
</form>
Documentation: https://api.jquery.com/submit/
I'm working on a project. I'm trying to make my code so that when a user submits an option from a dropdown menu, if the user selects and submits the default ("Select a genre"), the form is not submitted and the page is not refreshed. Following is my Javascript code:
<script>
var menu = document.getElementById("submit");
menu.addEventListener("click", function() {
if (document.getElementById("dropdown").value == 'nothing')
{
return false;
}
});
</script
This is nested inside a head tag.
Following is my HTML code for the form:
<div>
<form method="POST">
<select id="dropdown" name="genre">
<option value="nothing">Select a genre</option>
<option value="rock">Rock</option>
</select>
<br/>
<br/>
<input id="submit" type="submit"/>
</form>
</div>
The javascript doesn't seem to work, since even when I submit the form while selecting the "Select a genre" option, my form is still submitted, and the python code does work on the value 'nothing', which gives errors.
EDIT: Upon adding further functionality to my project by adding more javascript code, the javascript code again didn't work. I used google chrome's developer tools and stumbled upon this error which seems to be related to why the code isn't working:
Uncaught TypeError: $(...).addEventListener is not a function
at (index):18
Try event.preventDefault():
var menu = document.getElementById("submit");
menu.addEventListener("click", function(event) {
if (document.getElementById("dropdown").value == 'nothing')
{
event.preventDefault();
}
});
<div>
<form method="POST">
<select id="dropdown" name="genre">
<option value="nothing">Select a genre</option>
<option value="rock">Rock</option>
</select>
<br/>
<br/>
<input id="submit" type="submit"/>
</form>
</div>
It is just a declaration of Code if you don't bind to $( document ).ready() or make it as self-invoking function.
First solution:
$( document ).ready(functino(){
var menu = document.getElementById("submit");
menu.addEventListener("click", function() {
if (document.getElementById("dropdown").value == 'nothing')
{
return false;
}
});
});
Another Solution:
(function(){
var menu = document.getElementById("submit");
menu.addEventListener("click", function() {
if (document.getElementById("dropdown").value == 'nothing')
{
return false;
}
});
}());
I have a simple HTML document with a form I would like to post to the server without leaving the page. I've Googled around the internet all day trying to figure out how to get this to work and I've come up with the following code:
<body>
<script>
$(document).ready(function() {
$('#newResource').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'scripts/script.php?new-resource=1',
data: $('#newResource').serialize(),
success: function () {
alert('form was submitted');
}
});
return false;
});
});
</script>
<form id="newResource" class="form-basic" enctype="multipart/form-data" method="post" action="scripts/script.php?new-resource=1">
<label><b>Resource Name:</b></label>
<input class="input-text" type="text" placeholder="Enter the resource name..." name="name" id="name" autocomplete="off" required="">
<br>
<label><b>Resource URL:</b></label>
<input class="input-text" type="text" placeholder="Enter the resource URL..." name="url" id="url" autocomplete="off" required="">
<br>
<label><b>Resource Department:</b></label>
<p>Select the department this resource should belong to.</p>
<select class="input-select" name="department" id="department">
<option value="5">Human Resources</option>
<option value="1">Information Technology</option>
<option value="3">Marketing</option>
<option value="0">No Department</option>
<option value="6">Purchasing</option>
<option value="4">Sales</option>
</select>
<br>
<label><b>Resource Icon:</b></label>
<p>Select the icon image to be displayed with this resource.</p>
<select class="input-select" name="icon" id="icon">
<option value="bell.png">Alarm Bell</option>
<option value="chat-bubbles.png">Chat Bubbles</option>
<option value="chronometer.png">Chronometer</option>
<option value="database.png">Database Icon</option>
<option value="envelope.png">Envelope</option>
<option value="folder.png">File Folder</option>
<option value="analytics.png">Monitor with Line Graph</option>
<option value="pie-chart.png">Monitor with Pie Chart</option>
<option value="networking.png">Networking Heirarchy</option>
<option value="orientation.png">Orientation Arrow</option>
<option value="server.png">Server Rack</option>
<option value="settings.png">Settings Gears</option>
<option value="speedometer.png">Speedomoeter</option>
<option value="worldwide.png">World Wide Web Globe</option>
</select>
<br>
<div style="float: right;">
<button type="button" onclick="loadPrefs('resources');" class="form-button cancel">Cancel</button>
<button class="form-button submit" type="submit">Submit</button>
</div>
</form>
</body>
The code is all within the body tag.
The problem is that when I click the submit button I am redirected to the PHP action script. Does the script I have need to be in the head tag instead?
If I remove the action from the form then the script redirects to the same page but no data is submitted.
Here is the PHP script if necessary:
if(isset($_GET['new-resource'])){
// escape the SQL input for security
$name = mysqli_real_escape_string($conn, $_POST['name']);
$url = mysqli_real_escape_string($conn, $_POST['url']);
$department = mysqli_real_escape_string($conn, $_POST['department']);
$icon = mysqli_real_escape_string($conn, $_POST['icon']);
// Run the SQL query to add the new resource item
$sql = "INSERT INTO Resources (ID, ResourceName, ResourceURL, IconImg, Department) VALUES (NULL, '$name', '$url', '$icon', '$department');";
$conn->query($sql);
// Close the SQL connection
$conn->close();
}
I can't seem to figure out why this is not working. Any thoughts and feedback are appreciated.
The important info in your case was "The HTML form elements are added with AJAX". At $(document).ready(), the #newResource form element did not yet exist, so the event was never bound. In your working example you used event delegation: $(document).on('click', '.submit', function(e) {...}, this is the correct way setup event listeners for non-existing elements.
Your event handler is bound to the submit event of the form. By the time the form has been submitted, it's too late to stop the default synchronous HTML form submission.
Bind your handler to the to click event on the submit button, use event.preventDefault() and submit the form via Ajax:
$(document).ready(function() {
$('.submit').click(function (e) {
e.preventDefault();
var form = $('#newResource');
var action = form.attr('action');
var data = form.serialize();
$.ajax({
type: 'POST',
url: action,
data: data,
success: function () {
alert('form was submitted');
}
});
});
});
Please note, the way this is written, it will fire for any click of an element with a class of submit. Since you may have more than one form on your web page and more than one button with a class of submit, it's not good to have the form variable use a hard-coded ID selector.
If the HTML of all your website forms are always coded this same way, with the submit button inside of a div which is nested in the form, you could replace:
var form = $('#newResource');
with:
var form = $(this).parent().closest('form');
Now you can wrap that code in a function called "bindForms()" or whatever, and you have a generic recipe for handling all forms, provided that the HTML structure is always the same (or at least, to the extent that the submit button always has a class of submit and is always wrapped in a parent container which is a child of the form.
Ok, I've managed to get this following code to work:
<script type="text/javascript">
$(document).on('click', '.submit', function(e) {
debugger;
e.preventDefault();
var form = $(this).parent().closest('form');
var action = form.attr('action');
var data = form.serialize();
$.ajax({
type: 'POST',
url: action,
data: data,
success: function () {
loadPrefs('resources');
}
});
});
</script>
The HTML form elements are added with AJAX but so was the script element. I moved the script element to the top of the page so that it is static and no longer loaded with the form.
I seem to be having an issue with Jquery not displaying a hidden DIV after a selected form value is chosen. When a user clicks yes, I want the hidden div to then be revealed. Am I missing something? You can take a look here https://jsfiddle.net/73merxk9/
Javascript
<script>
$(document).ready(function() {
$('#permit').on('permit', function() {
$("#hiddenform").toggle($(this).val() == 'Yes');
}).trigger('permit');
});
</script>
Form
<div>
<label for="permit">Permit</label>
<select id="permit" name="permit">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</div>
<div id="hiddenform">
<div>
<label for="permit_submitted">Permit Submitted</label>
<input placeholder="Permit Input Here..." name="job_number" type="text" id="job_number">
</div>
</div>
There is no such event "permit". You need to listen onchange event instead. Then you need to compare select value with "1" because Yes is a label, not value:
$(document).ready(function () {
$('#permit').on('change', function () {
$("#hiddenform").toggle($(this).val() == '1');
}).trigger('change');
});
Demo: https://jsfiddle.net/73merxk9/1/
When some elements in a HTML form are initially disabled, but get enabled and their value changed afterwards, if user clicks the form's reset button, the values of those elements get restored to their initial values, but they're still enabled although they were disabled originally. Why is it so, and how can I ensure that form reset resets those elements to be disabled?
JSfiddle here: http://jsfiddle.net/d872N/
Code example here:
<html>
<head>
<script>
function enableDisable()
{
var combo1 = document.getElementById("a");
var combo2 = document.getElementById("b");
if (combo1.value == 1)
combo2.disabled = true;
else
combo2.disabled = false;
}
</script>
</head>
<body>
<form name="form" action="dummy">
<select id="a" onchange="enableDisable();">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select disabled id="b">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit" value="submit" />
<input type="reset" value="reset" />
</form>
</body>
</html>
The reset() method only restores a form elements default values and will not change the disabled state.
Read some documentation here https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.reset
I would suggest that you need to write your own reset method which calls HTMLFormElement.reset() and then resets the disabled state.
e.g.
New JavaScript code:
var hardReset = function(){
document.forms["form"].reset();
document.getElementById("b").setAttribute("disabled","disabled");
};
New HTML:
<input type="button" value="reset" onclick="hardReset();" />
Please see an update of your jsFiddle
A form element's disabled status, like other form-only attributes such as pattern, required, etc, is not part of the form's input data, which is the only aspect of form state which the reset method affects.
I came up against a similar problem a while back and decided to build a tool which would save states of DOM elements to revert them at will, thus keeping the DOM 'versioned'.
It's called a jQuery plugin called reverter and may help you out:
$( function form(){
// Save state on load
var initial = $( 'form *' ).commit( { attributes : 'disabled' } );
$( 'form' ).on( 'reset', function(){
// Revert it on reset!
$( 'form *' ).revert( { changeset : initial } );
} );
} );