I'm able to pass the displayMessage variable, but the page reloads. I've been looking at ajax tutorials, but I'm not sure how to pass displayMessage without the page reloading.
I want to store more than one message on the phone. So if I send "help me stackoverflow," then "please," they both get stored. (right now "please" would replace "help me...").
// this is my form
<form role="form">
<div class="form-group">
<textarea class="form-control" id="message" rows="3"></textarea>
</div>
<button type="submit" id="submit" class="btn btn-default">Submit</button>
</form>
// this is where message displays
<span class="displayMessage"></span>
// this is my js
$(document).ready(function () {
$('#submit').click(function () {
var displayMessage = $('#message').val();
localStorage.displayMessage = displayMessage;
});
});
$(document).ready(function () {
$('.displayMessage').html(localStorage.displayMessage);
})
The page reload is triggered by the default button click behaviour. You need to disable it by calling preventDefault on the event object:
$('#submit').click(function (e) {
e.preventDefault();
// your code
});
As DontVoteMeDown already said, you can store an object or array as JSON in the local storage. So you could do something like this:
$(document).ready(function () {
$('#submit').click(function (e) {
e.preventDefault();
var storedMessagesJSON = localStorage.displayMessages || '[]',
storedMessages = JSON.parse(storedMessagesJSON),
displayMessage = $('#message').val();
storedMessages.push(displayMessage);
localStorage.displayMessages = JSON.stringify(storedMessages);
});
var storedMessagesJSON = localStorage.displayMessages || '[]',
storedMessages = JSON.parse(storedMessagesJSON);
$('.displayMessage').html(storedMessages.join('<br>'));
});
I also made a JSFiddle.
Related
I need to keep the values of the rangeSlider after refreshing the page, as the selected range is reset. Local storage in my case for some reason doesn't work.
HTML Markup:
<input type="text" class="js-range-slider" name="my_range" value="" data-min="100" data-max="4000" data-from="1000" data-to="2000"/>
<input type="hidden" id="startPrice" name="startPrice" value="" />
<input type="hidden" id="endPrice" name="endPrice" value="" />
<button class="filter-btn_send filter-btn_send--active" type="submit">Select</button>
Code:
$(document).ready(function () {
if (localStorage.getItem('startPrice')) {
$('.js-range-slider').data('from', localStorage.getItem('startPrice'));
$('#startPrice').attr('value', localStorage.getItem("startPrice"))
}
if (localStorage.getItem('endPrice')) {
$('.js-range-slider').data('to', localStorage.getItem('endPrice'));
$('#endPrice').attr('value', localStorage.getItem("endPrice"))
}
$('.filter-btn_send filter-btn_send--active').submit(function () {
let startPrice = $('#startPrice').attr('value');
let endPrice = $('#endPrice').attr('value');
localStorage.setItem('startPrice', startPrice);
locacStorage.setItem('endPrice', endPrice);
});
}
UPD! My solution: https://codepen.io/funn1k1/pen/qBqMmgx
submit events
Submit events are fired on form objects, not buttons or input elements that trigger submission (as covered in MDN documentation. The following snippet shows that, as posted, the submit handler is not called by monitoring "submit" events on the submit button - the expected outcome is that only the form submit handler will be called:
"use strict";
$(document).ready(function () {
$('form').submit(function(e) {
console.log( "form submit handler called");
e.preventDefault();
});
$('input').submit( function(e) {
console.log( "submit button handler called");
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- body-html -->
<form>
<input type="submit">
</form>
beforeunload event
The "beforeunload" event can be monitored to save slider values when the page is unloading, even if the form has not been submitted. As a code pattern example:
$(document).ready(function () {
window.addEventListener("beforeunload", function(event) {
// get values from range widget
let startPrice = "1000" // example only
let endPrice = "1174" // example only
// save in localStorage
localStorage.setItem('startPrice', startPrice);
localStorage.setItem('endPrice', endPrice);
});
});
Note this doesn't include code to create, set or get the values of dual pointer jQuery-UI range widgets.
I want to increment the value of the name attribute whenever the function is called. Below I have added all the code through which I add new text boxes using jQuery clone function. Hope now everything is clear.
function addQuestion(){
var question = jQuery('#question-template').clone();
question.css("display","block").removeAttr('id');
jQuery('#questions').append(question);
}
function renameQuestions(){
jQuery('.question-box').each(function(i,v){
jQuery(this).find('.question_id').html(i);
});
}
jQuery('#add-question').on('click', function(e) {
e.preventDefault();
addQuestion();
renameQuestions();
});
jQuery(document).on('click','.del-question', function(e)
{
e.preventDefault();
jQuery(this).closest('.question-box').remove();
renameQuestions();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="quiz[0][english][ques_title]" class="ques_title" placeholder="Enter question title" value="">
<textarea name="quiz[0][english][ques_desc]" class="ques_desc" rows="4" placeholder="Explaination here...."></textarea>
<a id="add-question" class="button" href="#">Add</a>
<a class="del-question button" href="#" data-id="1">Remove</a>
I want to increment the value quiz[0], whenever the add-question button is clicked, I tried using PHP adding a PHP variable in the JS function. But then I got to know it will not work because one is server side and other is client side scripting.
Demo: http://jsfiddle.net/GCu2D/5163/
JS:
function renameQuestion() {
var question = $(".question-box:last");
var total_question = parseInt((".question-box input:first").attr("name").replace( /^\D+/g, ''))+1;
question.find("input").each(function() {
var elem = $(this);
elem.attr("name", elem.attr("name").replace(/[0-9]/g, total_question));
});
}
This should solve your issue.
I have several forms on my page with the same structure and classes.
I want to send form data to the server using POST method, and show error message if something went wrong.
So, HTML code for the forms:
<form class="js-form">
<input name="data" type="text" required>
<button type="submit" value="Go">Go Form 1</button>
</form>
<div class="js-alert" style="display:none;">Error Message</div>
<br><br><br>
<form class="js-form">
<input name="data" type="text" required>
<button type="submit" value="Go">Go Form 2</button>
</form>
<div class="js-alert" style="display:none;">Error Message</div>
and the js code:
$(document).ready(function() {
$(".js-form").submit(function(event) {
event.preventDefault();
var data = $(this).find("input[name='data']").val(),
url = "/api/method";
var posting = $.post(url, {data: data});
posting.done(function(res) {
$("input[name='data']").val(''); // empty all inputs in all forms
console.log(res);
});
posting.fail(function(res) {
// here I want to show the alert
// that is next to a form user had interacted with
});
});
I've tried $.proxy and this binding, but the context in posting.fail() is always the same (request context). How could I get to the form context and query closest alert sibling?
You have a few options:
Utilize the event argument to the submit callback (event.target points to the form):
posting.fail(function(res) {
console.log('do something with form', event.target)
});
Capture the context this into a variable outside of your posting.fail callback:
$(document).ready(function() {
$(".js-form").submit(function(event) {
event.preventDefault();
// capture context!
var form = this;
var data = $(this).find("input[name='data']").val(),
url = "/api/method";
var posting = $.post(url, {data: data});
posting.done(function(res) {
$("input[name='data']").val(''); // empty all inputs in all forms
console.log(res);
});
posting.fail(function(res) {
console.log('do something with form', form)
});
});
If you can support ES6, this is much simpler - just use an arrow function:
posting.fail((res) => {
console.log('do something with form', this)
});
You can use $(this) as this will reference the form that was submitted.
However, since the scope of this in your callback will be different you will need to define it outside the callback function.
var that = $(this);
so your code will look like this:
var that = $(this);
//rest of code
posting.fail(function(res) {
$(that).html(res);
});
See complete code snippet below:
$(document).ready(function() {
$(".js-form").submit(function(event) {
var that = $(this); //reference to form submitted on
event.preventDefault();
var data = $(this).find("input[name='data']").val(),
url = "/api/method";
var posting = $.post(url, {
data: data
});
posting.done(function(res) {
$("input[name='data']").val(''); // empty all inputs in all forms
console.log(res);
});
posting.fail(function(res) {
//can now reference the form submitted here
that.html(res);
});
});
You can set the context option of $.ajax() settings to an object, where this should be the same object set at the value for context property within jQuery .then(), .done(), .fail() and other deferred methods. Not sure how code used $.proxy, though that is also an option that can be used.
$.ajax({/* settings, */ context:{} /* set `this` here */})
.then(function() {
// `this` : `this` set at `context`
})
.fail(function() {
// `this` : `this` set at `context`
})
I am submitting a form using AJAX. The fields are in a partial view that get sent to a controller action. The partial view is in a div that pops up when a button on the main form is clicked. If the user completes the form and clicks the submit button it then the update is performed in the controller action and all is well. However, if the user changes their mind I like to add a cancel button to hide the form. Adding the button and hiding the form works as expected, but the call to the controller action method still occurs. I've tried using
e.preventDefault();
but this hasn't worked.
I've tried using a second JQuery method attached to the cancel id but I can't get this to work.
My JQuery looks like this:
$('#VisitorModal').on('submit', '#visitorform', function (e) {
var data = $(this).serialize();
var url = '#Url.Action("CreateVisitor", "Meetings")';
var text = $('#title').val() + ' ' + $('#firstname').val() + ' ' + $('#surname').val() + ' (' + $('#company').val() + ')'; // a value from the form that you want as the option text
$.post(url, data, function (response) {
if (response) {
$('#VisitorID').append($('<option></option>').val(response).text(text)).val(response);
} else {
dialog.hide();
}
}).fail(function () {
dialog.hide();
});
dialog.hide();
e.preventDefault();
//return false; // cancel the default submit
});
$('#cancel').on('click', function () {
dialog.hide();
});
And here's my action method:
[HttpPost]
public JsonResult CreateVisitor(AppointmentViewModel model)
{
var visitor = new Visitor()
{
Title = model.VisitorTitle,
FirstName = model.VisitorFirstName,
LastName = model.VisitorSurname,
Company = model.VisitorCompany
};
db.Visitors.Add(visitor);
db.SaveChanges();
return Json(visitor.id);
}
And submit & cancel buttons here:
<div class="form-group">
<div class="col-md-offset-2 col-md-5">
<input type="submit" value="Create" class="btn btn-success" id="submit" />
<input type="button" value="Cancel" class="btn btn-warning" id="cancel" />
</div>
</div>
Does anyone have any suggestions that might get this to work as I hope?
Since your form is being loaded dynamically after the initial page has been rendered, you need to use event delegation by using .on() to add a listener to an ancestor that exists when the page is rendered
Instead of
$('#cancel').on('click', function () {
dialog.hide();
});
use
$(document).on('click', '#cancel', function () {
dialog.hide();
});
but replace document with the closest ancestor that exists when the page is first generated.
this is a part of my html:
<p>City: <input type="text" id=city value="New York"> </p>
<p>State: <input type="text" id=state value="NY"> </p>
<button id="search">Search!</button>
<button id="favorite">mark as favorite!</button>
Bellow is my .js
The search function is working like a charm, it does an ajax call with the inputs and receive weather infos.
my problem is with the favorite button, what i need is to search for example Baltimore and click on Mark as favorite. This will make Baltimore to be the one to opens when I refresh the page.
I believe that one alternative would be changing the standard input text because my ajax call is made when document its ready or when search button is clicked but i have no idea how to do it yet.
$('#search').click(function() {
ajax();
});
$('#favorite').click(function() {
var $city= $('#city')
document.getElementById('city').value= $city.val();
});
any ideas??
edit: solution:
$(document).ready(function() {
var $city= $('#city')
document.getElementById("city").value = localStorage.getItem("city");
ajax();
});
...
...
...
$('#favorite').click(function() {
var $city = $('#city')
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("city", $city.val() );
// Retrieve
document.getElementById("city").innerHTML = localStorage.getItem("city");
} else {
document.getElementById("city").innerHTML = "not possible to store";
}
ajax();