Reputation: 1791
I'm trying to use jQuery cookie to set languages. I have the following form:
<select id="lang">
<option value="en_US">English</option>
<option value="it_IT">Italiano</option>
<option value="fr_FR">Français</option>
</select>
<input id="btn" type="button" value="submit">
<noscript><input id="btn" type="button" value="submit"></noscript>
Within the following script:
// Set cookie
$(document).ready(function () {
$("#btn").on("click", function () {
$.cookie('lang_cookie', $("#lang").val(), { expires: 365 });
});
});
The form above works nicely but I'd like to remove the button and auto-submit.
I can change the form using onchange="this.form.submit()"
:
<select id="lang" onchange="this.form.submit()">
<option value="en_US">English</option>
<option value="it_IT">Italian</option>
</select>
But what about the jQuery part? How can I set cookies without using $("#btn").on("click", function (){})
?
Upvotes: 1
Views: 987
Reputation: 1
// Set cookie
$(document).ready(function () {
$("THE ID OF YOUR FORM").submit(function () {
$.cookie('lang_cookie', $("#lang").val(), { expires: 365 });
});
});
Upvotes: 0
Reputation: 4364
Your html
<select id="lang" onchange="return setC(this);">
<option value="en_US">English</option>
<option value="it_IT">Italiano</option>
<option value="fr_FR">Français</option>
</select>
Your script
function setC(elem)
{
$.cookie(...);
elem.form.submit();
}
Upvotes: 1
Reputation: 14429
You can set the cookie and then submit the form:
// Set cookie then submit
$(document).ready(function () {
$("#btn").on("click", function() {
$.cookie('lang_cookie', $("#lang").val(), { expires: 365 });
$("#btn").closest('form').submit();
});
});
Using jQuery .submit().
Upvotes: 0
Reputation: 2517
You can directly use the onchange event without submitting the form as below,
<select id="lang" onchange="set()">
<option value="en_US">English</option>
<option value="it_IT">Italian</option>
</select>
Now you can write your script as,
function set(){
$.cookie('lang_cookie', $("#lang").val(), { expires: 365 });
}
Upvotes: 1