I am working in wordpress and I have an html form with two submit buttons with same classname and different value. I am passing the submit button clicked value through ajax and show it on the screen. Now my problem is that only first submit button value goes through and second submit button value never gets to show on the screen. Kindly guide and below is my code.
Code
<form id="mydispimage" action="" method="post">
<select id="category" style="width: 250px; background-color: lightgrey;" name="category">
<option disabled="disabled" selected="selected" value="">Select category</option>
<option value="Cutie Pie">Cutie Pie</option>
<option value="Chubby">Chubby</option>
<option value="Dimples">Dimples</option>
</select>
<input class="displayimage" name="displayimage" type="submit" value="star1" />
<input class="displayimage" name="displayimage" type="submit" value="star2" />
</form>
JQuery
jQuery(function ($) {
$(".displayimage").click(function (e) { //form is intercepted
e.preventDefault();
//show timer
jQuery("#timer").css("display", "block");
jQuery("#participate").css("display", "block");
var vote = jQuery(".displayimage").val();
alert(vote);
//$("#timer").show(slow);
//serialize the form which contains secretcode
// var sentdata = $(this).serializeArray();
//var vote = 1;
//Add the additional param to the data
var sentdata = ({
action: 'displaymyimage',
foo: vote
})
//set sentdata as the data to be sent
$.post(yes.ajaxurl, sentdata, function (res) { //start of funciton
//$("#myresult").append(res.l);
//alert(res);
$("#myresult").html(res);
//$.parseJSON(data);
return false;
} //end of function
,
'json'); //set the dataType as json, so you will get the parsed data in the callback
}); // submit end here
});
Change this
var vote= jQuery(".displayimage").val();
to this
var vote= jQuery(this).val();
You need to use $(this). Otherwise, you will always bring the first value among the elements with matching .displayimage class. That is why you see always the value of the first button.
Related
I have big trouble now. I am trying to make a small script with plain JavaScript. But I have one problem. If I click on button, nothing happens (but alert works). It seems to be like the page just refresh, because the console log doesn't work too.
<form>
<select class="select" id="test">
<optgroup>
<option selected disabled hidden>Default</option>
<option value="1">Value 1</option>
</optgroup>
</select>
<button class="btn" onclick="myFunction();">text</button>
</form>
function myFunction() {
var e = document.getElementById("test");
var strUser = e.options[e.selectedIndex].value;
if (strUser > 0) {
window.location.href = 'www.google.com';
} else {
alert("Error")
}
}
Your button is inside a form. Clicking it will submit the form.
So your onclick function runs, begins navigation to www.google.com (a URL which is missing the scheme), and then the form submits and begins navigation to the form's action (which is unspecified, so defaults to the URL of the current page).
The second navigation overrides the first, so you load the current page again instead of www.google.com.
You need to cancel the default behaviour of the form submission or the submit button.
Using the 1990s approach you are currently using:
<button class="btn" onclick="myFunction(); return false">
Or using modern code:
document.querySelector("form")
.addEventListener("submit", myFunction);
and
function myFunction (event) {
event.preventDefault();
// etc
getElementbyId just takes the string, it does not include the "#".
#Ondřej Musil, you have to take care when you ask something to don't forget about put details and a more complete code.
I think that I have your answer! But let me know if is that are you trying...
Do you have a Button and a Select? When you perform a click in the button, the will be called that function, right?
HTML
<button onclick="myFunction()"> Redirect </button>
<select id="test">
<option value="1" selected="selected">User 1</option>
<option value="2">User 2</option>
</select>
JS
function myFunction() {
var e = document.getElementById("test");
var strUser = e.options[e.selectedIndex].value;
if (strUser > 0) {
window.location.href = 'http://www.google.com';
} else {
alert("Error")
}
}
Please, try it!
I have these 2 drop downs:
I have to provide values of Select Item drop down based on the value chosen in the Select Category drop down.
This is my PHP for Select Category drop down:
<form>
...
<select name="category" id="category" value="category" class="form-control ddplaceholder" style="width:220px;font-size:18px;font-family:Roboto;" onclick="document.form.submit();">
<option value="" disabled selected>Select Category</option>
...
<input type="submit" name="submit" style="width:20%;padding:15px;" value="Update"</input>
...</form>
But nothing is happening. How do I do it?
Try onchange instead of onclick
<form>
...
<select name="category" id="category" value="category" class="form-control ddplaceholder" style="width:220px;font-size:18px;font-family:Roboto;" onchange="document.forms[0].submit();">
<option value="" disabled selected>Select Category</option>
...
<input type="submit" name="submit" style="width:20%;padding:15px;" value="Update"</input>
...</form>
Two more things you should notice
onchange="document.form.submit();" this will not work because
document doesn't have a property form it is forms so you should
use onchange="document.forms[0].submit();"
You have named your submit button as submit which will prevent the
form from submitting because submit is a javascript function so
rename your submit button to something else.
If you dont have many possible values for your dropdowns, you can use plain old javascript for that purpose. See this http://jsfiddle.net/mplungjan/65Q9L/, but it requires all values to be loaded at once on the page load like this:
var stateObject = {
"California": {
"Monterey": ["Salinas", "Gonzales"],
"Alameda": ["Oakland", "Berkeley"]
},
"Oregon": {
"Douglas": ["Roseburg", "Winston"],
"Jackson": ["Medford", "Jacksonville"]
}
}
document.form.submit(); will submit the form which is not the requirement.
Instead you need to make an ajax call with the selected value from first dropdown and the response will be use to build the options of second dropdown.
use change which will trigger on change of option
$('category').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value; // will give value of selected option
$.ajax({
url:"someUrl", // this url will return response from backend
// other methods
success:function(response){
//use this response to build the second dropdown
}
})
});
E.g. I have an HTML form:
<form role="search" method="get" id="searchform" action="" >
<!-- DIRECT SEARCH INPUT TO SEARCH STRING -->
<input type="text" value="" name="s" id="s" />
<input type="submit" id="searchsubmit" value="Search" />
<!-- DROPDOWN TO SELECT ONE CHOICE -->
<select name='country' id='country' class='postform' >
<option class="level-0" value="2">USA</option>
<option class="level-0" value="3">Canada</option>
<option class="level-0" value="4">Mexico</option>
<option class="level-0" value="5">Cuba</option>
</select>
<!-- CHECKBOXES TO SELECT MULTIPLE CHOICES -->
<div id="color">
<input type="checkbox" name="" value="21" />Beachfront
<input type="checkbox" name="" value="16" />TV
<input type="checkbox" name="" value="20" />Internet
<input type="checkbox" name="" value="17" />Pets Allowed
</div>
</form>
<div id="results"><!-- THE AJAX RESULTS GOES HERE --></div>
And I want to be able to make AJAX request every time the user:
1) write something in the search input box and click search button
OR
2) select one choice from the dropdown menu
OR
3) select one or multiple choices from the checkboxes that are checked
The problem is that I don't know how to structure my JavaScript code correctly and what is the best way to remember and manage choices that the user selected before, to take all things in account. For example, not just the search term when he write something and click search button, but also to take in count the dropdown choice (probably done one step before) and maybe the checked options from checkboxes if he has checked something before. Here is what I have so far:
jQuery(document).ready(function($){
// RESULTS SHOULD APPEAR IN #results DIV AFTER AJAX IS DONE
var $maincontent = $('#results');
// SEARCH INPUT PROCESSING
$('#searchsubmit').click(function(e){
e.preventDefault();
var searchval = $('#s').val();
$.post(
WPaAjax.ajaxurl,
{
action : 'ajax_search_action_do',
searchval : searchval
},
function( response ) {
$maincontent.empty();
$maincontent.append( response );
}
);
});
// COUNTRY DROPDOWN CHOICE PROCESSING
$('#country').on('change', function() {
var countryval = this.value;
$maincontent.animate({ opacity : '0.1' })
$.post(
WPaAjax.ajaxurl,
{
action : 'ajax_search_action_do',
countryval : countryval
},
function( response ) {
$maincontent.empty();
$maincontent.append( response );
$maincontent.animate({ opacity : '1' })
}
);
return false;
});
// CHECKBOXES PROCESSING
$('#color input[type=checkbox]').click(function() {
if (this.checked) {
// code if checked
}
else {
// nothing
}
});
});
As you can see, it's very bad. Because one "function" checks only click, one change and I don't know how to grab values from the checkboxes and make an array and send it via ajax ;(.
Any idea how to structure the JavaScript code so it is not so separated and the checks are somehow in one part (or more logical) instead of three separated parts?
Any ideas are welcome.
Create som logic :
var _do = {
bind: function() {
var self = this;
$('#searchsubmit').on('click', function(e){
e.preventDefault();
self.ajax('searchval', $('#s').val());
});
$('#country').on('change', function() {
self.ajax('countryval', this.value);
});
return self;
},
ajax: function(key, value) {
var data = {action: 'ajax_search_action_do'};
data[key] = value;
$.post(
WPaAjax.ajaxurl, data, function( response ) {
$maincontent.empty().append( response );
}
);
}
}
jQuery(document).ready(function($){
_do.bind();
});
Maybe use jquery.form.js?
http://malsup.com/jquery/form/
It's a great plugin, just structure the form like it was a normal redirection form, add array in name of checkboxes
<input type="checkbox" name="types[]" value="21" />Beachfront
Add target URL to the form, and then...
When u want to submit the form just do
$('searchform').ajaxSubmit({
success: function() {
// callback
}
)
Trigger this on checkboxes change, dropdown change etc. To make the code clean, use one selector
$('#country, #s, #color input').on('change', sendAjaxForm);
This is to check if a user is opening another div (form; there are four for the page) without having saved the entry or update for the current form.
I need to compare the current value of dropdowns to all the possible choices of the dropdowns. If there is a difference the user is shown an alert notifying of having not saved the data. There is a not a set number of dropdowns. My script has been able to correctly count the number of dropdowns for each form.
Thanks,
James
You can do this by updating a variable on change of your select and then checking that value whenever you do what it is you do to move on to the next form. Here's the code I have mocked up:
HTML -
<select id="one">
<option value=""></option>
<option>1</option>
<option>2</option>
</select>
<br />
<select id="two">
<option value=""></option>
<option>3</option>
<option>4</option>
</select>
<br />
<select id="three">
<option value=""></option>
<option>5</option>
<option>6</option>
</select>
<br />
<!-- The submit buttons -->
<input type="submit" id="submit" value="Save" />
<br />
<!-- The link that moves on to the next form -->
Move on
Javascript -
// the variable
var selectChanged = false;
// set up everything on load
window.onload = function() {
// bind handlers to submit button, link, an dselects
document.getElementById("submit").onclick = submitForm;
document.getElementById("moveOn").onclick = moveOn;
var selects = document.getElementsByTagName("select");
var numSelects = selects.length;
for (var i = 0; i < numSelects; i++) {
selects[i].onchange = noteChanged;
}
}
function submitForm() {
// set the changed variable to false
selectChanged = false;
}
function moveOn() {
// if the select has changed without save, alert the user and prevent
// link actions
if (selectChanged) {
alert("You have changed a form value but not saved it");
return false;
}
}
// update the value for each time a select changes
function noteChanged() {
selectChanged = true;
}
Here it is in action
What I would do is:
Whenever a change happens (you can attach to the onChange event for any form elements you need to track), set a flag somewhere that indicates the form (or whatever) is "dirty". (a good place to put this is in data- attributes)
When the form gets saved, the saving process can re-set the dirty flag to clean
Whatever method is used to switch forms can check first to see if the dirty flag is set, and if so, display an error (or warning) and prevent the next form from being shown.
With these 3 pieces in place, you should be able to easily detect a dirty (unsaved) form and take the appropriate actions.
I want to use a select to change the query on the end of a url to change it's sort options. e.g:
<select id="sort">
<option value="?order_by=date">Recent</option>
<option value="?order_by=random">Popular</option>
<option value="?order_by=random">Random</option>
<option value="">Staff Picks</option>
</select>
so for example by default a list of posts will be shown by date and then if a user chooses an option it will reload the page with the query string on the end of the URL. If possible looking to use jQuery to achieve this. Thanks.
Attach a handler to the change event for the select box that adds the value of the selected option to the current window location with everything after the ? snipped off:
$('#sort').change(function(e){
var locAppend = $(this).find('option:selected').val(),
locSnip = window.location.href.split('?')[0];
window.location.href = locSnip + locAppend;
});
Here's an example (it doesn't redirect, but you get the idea...)
To have the appropriate value selected on page load, you can run the following function before you bind the change handler:
function selectCurSort() {
var match = window.location.href.split('?')[1];
$('#sort').find('option[value$="'+match+'"]').attr('selected',true);
}
selectCurSort();
I'm not quite sure why you aren't just using something like:
<form method="GET">
<input type="hidden" name="query" value="..." />
<select id="sort" name="order_by">
<option value="date">Recent</option>
<option value="popular">Popular</option>
<option value="random">Random</option>
<option value="staff">Staff Picks</option>
</select>
<input type="submit" value="Sort" />
</form>
And, for the JS, if any, just:
$('#sort').change(function() {
$(this).parents('form').submit();
});
Then, you don't require anyone to have JavaScript enabled.
Like this?
$("#sort").change(function(){
window.location = $(this).find("option:selected").val();
});
Add
onchange="if (this.value && /^\?/.test(this.value)) location = location.path + this.value"
to your <select>.
You might want to put a blank option at the top too.
$(function() {
$("#sort").change(function() {
var myVal = $(this).val();
window.location = "www.mywebsite.com/"+ myVal;
});
var qs = window.location.pathname;
$("#sort option").each(function() {
if(qs.contains($(this).val()))
$(this).addAttr("selected","selected");
});
});
Try that.