I have a three dropdown with 1 submit button. Now, I'm trying to retain the value of each dropdown after the user clicked the input submit. But the Jquery I have is not working. I use PHP to displayed the output of the dropdown when the user clicked it.
Note: The page is refresh when the user clicked the input submit.
How to fix this? See in plunker
JS:
$(document).ready(function(){
$('#dropdown').change(function(){
var option = $(this).find('option:selected').val();
$('#dropdown').val(option);
});
});
Use local storage with all option;
$("#dropdown").change(function(){
var html=$("#dropdown").html();
localStorage.setItem("myapp-selectval",html);
localStorage.setItem("myapp-selectvalselected",$("#dropdown").val()); //to retain selected value
})
Now on document load;
window.onload=function()
{
if(localStorage.getItem("myapp-selectval")!="" && localStorage.getItem("myapp-selectval")!=undefined)
{
$("#dropdown").html(localStorage.getItem("myapp-selectval"));
$("#dropdown").val(localStorage.getItem("myapp-selectvalselected")); //to get previously selected value
}
}
Once again as I said in comment it's not a good solution.
You can get the values easily by making use of the model attribute present in the select element.
First add a onclick function like so
<input type="submit" name="submit" value="Submit" onclick="getValues()"/>
Then get the value on submit of the button(Entire code) Plunkr
I had a look at your code, the way your selectbox rendering is setup we have to explicitly call the updateSelect() function for the options to work well. This function makes your selectbox "dynamic".
var first = localStorage.getItem("firstDropDown");
var second = localStorage.getItem("secondDropDown");
var third = localStorage.getItem("thirdDropDown");
if(first !== null && second !== null && third !== null) {
setValues(); //this should come after getting the values above
}
function getValues() {
var first = document.getElementsByTagName("SELECT")[0].getAttribute("model");
var second = document.getElementsByTagName("SELECT")[1].getAttribute("model");
var third = document.getElementsByTagName("SELECT")[2].getAttribute("model");
localStorage.setItem("firstDropDown", first);
localStorage.setItem("secondDropDown", second);
localStorage.setItem("thirdDropDown", third);
}
//on load when this function is called globally, the values from the localStorage will be set to the dropdown values.
function setValues() {
//for first dropdown
document.getElementsByTagName("SELECT")[0].setAttribute("model", first);
document.getElementsByTagName("SELECT")[0].value = first;
updateSelect(document.getElementsByTagName("SELECT")[0]);
//for second dropdown
document.getElementsByTagName("SELECT")[1].setAttribute("model", second);
document.getElementsByTagName("SELECT")[1].value = second;
updateSelect(document.getElementsByTagName("SELECT")[1]);
//for third dropdown
document.getElementsByTagName("SELECT")[2].setAttribute("model", third);
document.getElementsByTagName("SELECT")[2].value = third;
updateSelect(document.getElementsByTagName("SELECT")[1]);
}
To retain the value you have no choice but to use a window.localStorage like so -
localStorage.setItem("firstDropDown", first);
localStorage.setItem("secondDropDown", second);
localStorage.setItem("thirdDropDown", third);
Then fetch the value
var first = localStorage.getItem("firstDropDown");
var second = localStorage.getItem("secondDropDown");
var third = localStorage.getItem("thirdDropDown");
If the user is going to refresh the page, your best bet is to have the server send down the value that the user just submitted with the new page load.
If that's impossible for some reason, you can use localStorage:
$(document).ready(function(){
var prevVal = localStorage.getItem('selectValue');
prevVal && $('#dropdown').val(prevVal);
$('#dropdown').change(function(){
var option = $(this).val();
localStorage.setItem('selectValue', option);
});
});
Keep in mind that not all browsers support this API yet.
EDIT: If you don't need the browser to refresh, you can use Ajax:
// ...
$('#myForm').submit(function (event) {
event.preventDefault();
var option = $('#dropdown').val();
var fd = new FormData();
fd.append('dropdown', option);
$.ajax('/path/to/form/target/', {
method: 'POST',
formData: fd
});
// ...
});
//...
Although I assume OP's question asks for a JS solution, I do want to bring something else to the table because I was also searching to solve the same problem. However, I ended up solving it in a manner that I considered to be satisfying.
In my case I'm using Flask as the backend, but I believe the solution should be at least similar for other use cases.
On the HTML where the dropdown is located, I pass a variable from the backend which is originally set to be some default value of my choice. Let's call this variable default_var_set_in_backend. This will ultimately be fed to the HTML and will look like as follows:
<select name="some_name_you_want" onchange="this.form.submit()">
<option selected="selected">{{ default_var_set_in_backend }}</option>
Once a change is made in the dropdown value by the user (in my case it's a GET request), I update the variable default_var_set_in_backend to be equal to this new choice. Now, the HTML will reflect the latest choice made by the user once the page refreshes.
Related
First post on Stackoverflow, be gentle.
Since I think my error lies somewhere in the logic and haven't found any similar questions I decided to go forward with it.
Situation as follows:
I have a global empty array called redirects.
var redirects = [];
redirects[] fills dynamically based on ajax response data
function ajaxFunction() {
within success call:
var prefix = "abc";
for (var key in data) {
var url = (prefix + key);
redirects[key.toLowerCase()] = url;
}
}
In my on-click method I bind the clicked class to it's url and call the function that creates a table; followed by the one that dynamically fills it based on our url.
/**
* Bind clicked class to url and call function to fill table.
*/
$(myid).on("click", "a", function () {
// Get the clicked class selector.
var clicked = $(this.getAttribute("class"));
var selectedClass = clicked.selector;
// Check for same value and break operation when found.
for(var key in redirects) {
if (key == selectedClass) {
// Set the url to redirect in fillTable function.
var url = redirects[key];
break;
}
}
// Returns values as we expect
// console.log(key, " | ", url);
// Construct a table based on url.
table();
fillTable(url);
});
FYI: table() displays a table form in html; fillTable() fills the th & td;
Both functions work fine with static url immediately defined but I want it dynamically based on the click.
Now, when I test this out, this only works when spamming the link quickly instead of just clicking it once.
This leads me to believe that the reason for it not showing up immediately, is because somehow the for-loop within my on-click is still running and requires the second click to be recorded (but I'm just guessing here).
So yesterday, I added some Jquery code and it worked perfectly. Today I was adding some more for a new part of my website and it did not work. When I tried the code I added yesterday, that stopped working as well. The first thing I do is create a function to get anything from the url that I need. The first 2 inputs are for following users. The first input should send the id variable to the url bar and is retrieved in the php file called follow.php. The second input should do the same thing. Finally the last function is for liking peoples posts. It sends the type of like(like or unlike) to the php file named like.php and is retrieved there. And should post the retrieved data into a div called likes. However, none of which is occurring when the buttons are pressed. Even when I just send an alert to make sure the on click is working, nothing happens either.
Here is my code:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$('input#sub').on('click', function(){
var id = getParameterByName('id');
$.get('follow.php' , {id: id}, function(data){
location.reload();
});
});
$('input#sub1').on('click', function(){
var id = getParameterByName('id');
$.get('unfollow.php' , {id: id}, function(data){
location.reload();
});
});
function doAction(postid , type){
alert("Works");
$.post('like.php' , {postid: postid type: type} , function(data){
$('div#likes').text(data);
});
}
Let's try to sum things up. I'm gonna change most of your code simply because you don't need all of that, otherwise jQuery wouldn't be helpful at all.
Assuming your caller is this anchor:
<img id="like" src="Social/down.png"/>
After this you can manipulate the clicked object getting its attributes easily through:
$('.idsfromdb').click(function(){
var id = $(this).prop('id');
var another_id_obj = $('newselector').prop('id');
// more logic, ajax,...
});
You can attach this kind of functions to every click event and then manipulate the object, call a php file, and so on... I hope I helped you somehow with this.
open google developer tools > network and see if request is made and if it has all data you want as request and if there is anything in response.
if there is request with all parameters, you have problem on server side,
if parameters not same that you are trying to send with ajax, than prevent buttons default action, you must prevent it every time when using ajax especially when button submits form.
$('input#sub').on('click', function(event){
event.preventDefault();
//your ajax
}
I've had a look at some other threads but nothing quite as specific. It's not really something that I would assume is hard but I'm not sure how about to do it.
Currently I'm using Select2 for a tagging system and next to it I have suggested tags which users would be able to click on and it will add to the box.
Instead, each tag is replacing the content and adding itself.
I need the adding to be appended into the box without replacing what's already in there.
Here's my code:
$(document).on('click', ".tag1", function () {
var value = $(".tag1").html();
console.log(value);
$("#selectPretty").val([value]).trigger("change");
});
$(document).on('click', ".tag2", function () {
var value = $(".tag2").html();
console.log(value);
$("#selectPretty").val([value]).trigger("change");
});
The data is being pulled through via AJAX with a span around each suggested tag.
Hope I'm clear enough.
Summary: I want to be able to click on each 'tag' and for it to be added, instead it replaces what was already in the box.
Thanks
You should be able to do that with simple:
var test = $('#test');
$(test).select2({
data:[
{id:0,text:"enhancement"},
{id:1,text:"bug"},
{id:2,text:"duplicate"},
{id:3,text:"invalid"},
{id:4,text:"wontfix"}
],
multiple: true,
width: "300px"
});
var data = $(test).select2('data');
data.push({id:5,text:"fixed"});
$(test).select2("data", data, true); // true means that select2 should be refreshed
Working example: http://jsfiddle.net/z96Ca/
You are replacing the value with val(mystuff). You want to do the following:
Get the current data in the input with val()
var dataOld = $('#selectPretty').val();
Append the new data with something like*
var dataNew = dataOld.push(value);
Set the input data to new data:
$('#selectPretty').val(dataNew);
*This assumes that val() returns an array
Docs
I am using Ajax/Jquery to display a dropdown menu with results from my SQL database. I'm using javascript to get a variable and then that variable is used within PHP. However it does not work.
I used Jquery .val() to get the variable from a select html tag when the user clicks the choices available.
Then, .on() to execute some php code depending on what the selected value from the dropdown box is.
My scenario is I have car classes (Sports, Hatchback) and cars available. What I am trying to do is, put the car classes in a dropdown box and then display the cars available dependent upon what the user has selected. I'm trying to do this using the above methods. (All this information is taken from a SQL database).
Has anyone got any solutions?
This is my my javascript code here:
<script>
var carid = $("#carid").val();
$("select[name='carid']").on("select",function(){$.post( "sDn.php", x, function( data ) { $( ".availablecar" ).append( data );});});
</script>
You probably want something like this
JavaScript
$("select[name='carid']").on("change", function() {
$.post(
"sDn.php",
{ carId: $("#carid").val() },
function(data) {
$(".availablecar").append(data);
}
);
});
PHP
$carId = $_POST['carId'];
You need to send the car id in the request and you probably need to bind to the change event, not select
You also need to get the car id value when the id has been changed, otherwise it will always remain the same value and never get updated when you change it
It appears to me that you are not using the carid variable anywhere. I think you mean to use carid instead of x
<script>
var carid = $("#carid").val();
$("select[name='carid']").on("select",function(){$.post( "sDn.php", carid, function( data ) { $( ".availablecar" ).append( data );});});
</script>
Also I would suggest parsing you form input if you don't already on the php side.
Try this:
$("#carid").on("change",function(e){
e.preventDefault();
var value = $(this).find("option:selected").val();
var $avaliable = $( ".availablecar" );
$.ajax({
url:'sDn.php',
type:'post',
data:{
'carid':value
},
dataType:'html',
success:function(result){
$avaliable.append( result );
}
});
});
Changed the $.post to $.ajax, passing the 'cardid' value.
Getting the selected option, on 'change'.
I'm unsure of the best practice for modifying the DOM based on an ajax response. I'll try to let the code do the talking because it's hard to explain.
// page has multiple checkboxes
$("input[type='checkbox']").live('click', function {
var cb = $(this); // for the sake of discussion i need this variable to be in scope
$("form").ajaxSubmit({ dataType: "script" });
}
The server sends a response back, and the js gets eval'd and that means "cb" is out of scope.
What I've done so far is create a couple of helper functions:
var target = undefined;
function setTarget(val) {
target = val;
}
function getTarget() {
return target;
}
And that turns the first snippet of code into this:
// page has multiple checkboxes
$("input[type='checkbox']").live('click', function {
setTarget($(this));
$("form").ajaxSubmit({ dataType: "script" });
}
Then on the server's response I call getTarget where I need to. This seems hackish... Any suggestions?
It's unclear what you're actually trying to do, but I feel like you want to be looking at the success parameter for that AJAX call. The success callback function should execute in parent scope and do what you're looking for.
See 'success' on this page in the jQuery docs.
So what you are trying to do is get the form to submit the content via ajax whenever the user checks/unchecks a checkbox? And because there are several checkboxes, you need to find out which one triggered the submit, so you can change its value to whatever is stored on the server?
If you submit the entire form everytime, why don't you reply with all the checkboxes values, and then change each and every one of them? If not, get the server to reply with the id and the value of the checkbox, then use jquery to find the checkbox with that ID and then change it's value.
How about:
jQuery(function($) {
// give it scope here so that the callback can modify it
var cb,
cbs = $('input[type="checkbox"]');
cbs.live('click', function {
// taking away var uses the most recent scope
cb = $(this);
// disable checkboxes until response comes back so other ones can't be made
cbs.attr('disabled', 'true'); // 'true' (html5) or 'disabled' (xhtml)
// unless you are using 'script' for something else, it's best to use
// a callback instead
$('form').ajaxSubmit({
success : function(response) {
// now you can modify cb here
cb.remove(); // or whatever you want
// and re-enable the checkboxes
cbs.removeAttr('disabled');
}
});
}
});