I have a problem whit my dropdown list,
I need to change location page when option selected using value option attribute, but the first option element not functional,
This is the html code:
<form>
<select class='language-select' name='URL' id='URL'>
<option value="index.php?lan=EN" selected> English</option>
<option value="index.php?lan=FR">Français</option>
</select>
</form>
and this is the Js function:
$('#URL').on('change', function(event){
event.preventDefault();
event.stopPropagation();
var $this = $(this);
window.location.href = $(this).val();
alert($(this).val());
});
also there an error ' uncaught exception: out of memory'
One thing, when i add an empty option element it works well, i can toggle bettwen two links: index.php?lan=FR and /index.php?lan=EN
Thanks
Your html marks the first option as selected no matter what. So, for example, when the French page is loaded, your dropdown still says "English". Instead, what you need to do is detect on page load which option should be selected. You can use a function like this:
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
And your markup would be:
<form>
<select class='language-select' name='URL' id='URL'>
<option id="EN" value="index.php?lan=EN"> English</option>
<option id="FR" value="index.php?lan=FR">Français</option>
</select>
</form>
Finally, in your jQuery on ready function, you would have:
$(function() {
var lan = GetURLParameter('lan');
$('#' + lan).prop('selected', true);
});
Hope it helps!
Related
In my HTML page i have 2 select.
When i change the value into the first select the second select must be change is option value.
Error in console :
Uncaught ReferenceError: Invalid left-hand side in assignment
If i add console.log(result) i see the object in console.
JS code
<script type="text/javascript">
function changeoption() {
$.getJSON('users.php', {nameUser:$('#nameUser').val()}, function(result) {
var select = $('#email');
var options = select.attr('options');
$('option', select).remove();
$.each(result, function(index, array) {
$('option', select) = new Option(array['email']); // the line error
});
});
}
$(document).ready(function() {
changeoption();
$('#userName').change(function() {
changeoption();
});
});
</script>
PHP code
<?php
$result = array();
if(isset($_GET['userName'])) {
$query = $dbh->prepare("SELECT email FROM tbl_users WHERE username = ? ORDER BY userId");
$query->execute(array($_GET['userName']));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($result);
?>
HTML code
<form>
<!-- first select populated by another query inside this page-->
<select name="userName" id="userName">
<option>Name1</option>
<option>Name2</option>
<option>Name3</option>
</select>
<!-- second select -->
<select name="email" id="email">
</select>
</form>
You're trying to assign to a jQuery object. Try creating the new option a different way.
instead of
$('option', select) = new Option(array['email']);
try
$('<option />', {
html: array['email'],
value: array['email']
}).appendTo('#email');
JSFiddle
You might use string append:
$('<option value="new">newOption</option>').appendTo("#email");
$('<option value="'+array['email']'+">'+array['email']+'</option>')
.appendTo("#email");
If you are a more php than jquery guy
you can put the select in a div
<div id='selecthtml'>
<select name="username" id="username">
<option>Name1</option>
<option>Name2</option>
<option>Name3</option>
</select>
</div>
then instead of getjson just use $.get
var url = "users.php?username"+$("#username").val();
$.get( url, function( data ) {
$( "selecthtml" ).html( data );
});
and of course your php users.php should return an html select (not json)
like this
<select name="username" id="username">
<option>New name 1</option>
<option>new name 2</option>
</select>
$('option', select) = new Option(array['email']); // the line error
In this line the $(...) is a function. You may be so used to using jQuery that you have lost sight of this. You cannot perform $(...) = ...; just like you cannot perform alert() = ...;
Change:
$('option', select).remove();
$.each(result, function(index, array) {
$('option', select) = new Option(array['email']); // the line error
});
});
to:
$(select).html('');
$.each(result, function(index, array) {
$(select).append(new Option(array['email']);
}
I have a simple select option box, the contents of which are generated from a PHP script. I looks like this
<form action="php/reloadNewList.php" method="POST">
<select name="listToGo" onchange="redirect(this.form.value)">
<?php
include('php/getMyList.php');
getList();
?>
</select>
</form>
The list generated looks fine
<option value="1">Hello</option>
<option value="12">Smelly</option>
etc
My JS script is simple enough as well
function redirect(value)
{
var x=value.selectedIndex;
alert("listToGo="+x + "\nValue = "+value);
document.cookie = "ListCookie="+x;
window.location.reload();
}
The problem I'm getting is that the onchange is not responding to the change on the drop down list.
Try to change:
<select name="listToGo" onchange="redirect(this)">
And:
function redirect(slct)
{
console.log(slct)
var x=slct.selectedIndex;
var value = slct.value;
alert("listToGo="+x + "\nValue = "+value);
document.cookie = "ListCookie="+x;
window.location.reload();
}
JSFiddle: http://jsfiddle.net/cherniv/YyUwR/1/
Try using this -
<select name="listToGo" onchange="redirect(this.value);">
This is the language select box.
<select name="lang" id="lang" browser="Indicated by the browser">
<option value="en">English</option>
<option value="fr">French</option>
<option value="ch">Chinese</option>
<option value="sp">Spain</option>`enter code here`
</select>
This is script i have written.
<script type="text/javascript">
jQuery(document).ready(function() {
loadBundles('en');
jQuery('#lang').change(function() {
var selection = jQuery('#lang option:selected').val();
loadBundles(selection != 'browser' ? selection : null);
jQuery('#langBrowser').empty();
if(selection == 'browser') { jQuery('#langBrowser').text('('+jQuery.i18n.browserLang()+')');
}
});
});
function loadBundles(lang) {
jQuery.i18n.properties({
name:'Messages',
path:'bundle/',
mode:'both',
language:lang,
callback: function() {
updateExamples();
}
});
}
function updateExamples() {
var ex1 = 'Firstname';
var ex2 = 'Lastname';
var ex3 = 'Youremail';
var ex4 = 'Reenteremail';
var ex5 = 'Newpassword';
var ex6 = 'Dateofbirth';
var ex7 = 'Signup';
var ex8 = 'Itsfreeandalwayswillbe';
var ex9 = 'Birthlabel';
var ex10 = 'Termslabel';
var ex11 = 'Summarylabel';
var ex12 = 'PersonalLabel';
var ex13 = 'Interestlabel';
var ex14 = 'Addlabel';
var ex15 = 'Editlabel';
var ex16 = 'Deletelabel';
var spreadsheet_label = 'Spreadsheetlabel';
var invite_google_label = 'Invitegooglelabel';
var invite_facebook_label = 'Invitefacebooklabel';
var upload_label = 'Uploadlabel';
var subBut='Submit';
var dialogTitle = 'DTitle';
jQuery("#first_name_label").text(eval(ex1));
jQuery("#first_name_label1").text(eval(ex1));
jQuery("#last_name_label").text(eval(ex2));
jQuery("#last_name_label1").text(eval(ex2));
jQuery("#email_label").text(eval(ex3));
jQuery("#email_label1").text(eval(ex3));
jQuery("#reenter_email_label").text(eval(ex4));
jQuery("#new_password_label").text(eval(ex5));
jQuery("#date_of_birth_label").text(eval(ex6));
jQuery("#date_of_birth_label1").text(eval(ex6));
jQuery("#sign_up").text(eval(ex7));
jQuery("#label1").text(eval(ex8));
jQuery("#button").val(eval(ex7));
jQuery("#birth_label").text(eval(ex9));
jQuery("#terms_label").text(eval(ex10));
jQuery("#summary_label").text(eval(ex11));
jQuery("#personal_label").text(eval(ex12));
jQuery("#interest_label").text(eval(ex13));
jQuery("#add_label").text(eval(ex14));
jQuery("#edit_label").text(eval(ex15));
jQuery("#delete_label").text(eval(ex16));
jQuery("#spreadsheet_label").text(eval(spreadsheet_label));
jQuery("#invite_google_label").text(eval(invite_google_label));
jQuery("#invite_facebook_label").text(eval(invite_facebook_label));
jQuery("#upload_label").val(eval(upload_label));
jQuery("#submit_button").val(eval(subBut));
jQuery("#ui-dialog-title-dialog").text(eval(dialogTitle));
}
</script>
Everything is working fine for the labels. But in the case of dynamic drop down i got problem. How to localize the dynamic drop down data when the user selected the language.
The data in the drop down is coming from the database.
I have a language select drop down box, after selecting one language from dropdown list am able to change the text filed names and all other text in the language that is selected.
At the same time i have another dropdown, in that data is generated dynamically form the database. After the user selecting the language from dropdown list i have to change the data in this drop down list also. please suggest me if u have any idea.
Thank you.
I suggest you to use ajax for this issue.
You can bind ajax to first drop down and then fill secound dropdown by data which you get from back-end.
You can do something like this :
<select name='lang'>
<option value='eng'>Eng</option>
<option value='french'>French</option>
</select>
<!-- below div is another div whose data changes as per the language selected -->
<div id="another_div"></div>
JS:
$("select[name='lang']").live({
change: function(e){
var selected_lang = $("select[name='lang'] option:selected").html();
data = {}
data['selected_lang'] = selected_lang;
$.ajax({
url: "required url",
data: data,
success: function(res){
$("#another_div").text(res); // if result is a direct text sent from server
// or
$("#another_div").text(res.content); //if result is an object with the required content present in the key 'content'
},
error: function(err){
alert("error occured");
}
});
}
});
I would use one of the many Cascading jQuery Dropdowns:
http://www.ryanmwright.com/2010/10/13/cascading-drop-down-in-jquery/
My project is in PHP / MySQL. I'm using Smarty for a template engine.
I have a < select > tag in my smarty file:
maps.tpl -
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<form method="post" action="maps.php">
<td colspan="3">
<select id="cmdview" name="cmd">
<option value=""></option>
<option value="commdata" {if $cmdOn == "commdata"}selected="true"{/if}>Communications</option>
<option value="contacts" {if $cmdOn == "contacts"}selected="true"{/if}>Contacts</option>
<option value="enrollment" {if $cmdOn == "enrollment"}selected="true"{/if}>Enrollment</option>
<option value="all" {if $cmdOn == "all"}selected="true"{/if}>All Schools</option>
</select>
<input type="submit" name="doSwitch" value="Submit" />
</td>
<div id="append"></div2>
</form>
So far, my jQuery code finds which value is selected:
{literal}
<script>
$('#cmdview').change(function() {
//alert('Handler for .change() called.');
var str = "";
url = "maps_append.php";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$('#append').text(str);
})
.change();
</script>
{/literal}
I need the jQuery to listen for the value of "cmdview" then post that value to file: maps_append.php . I need that file to .append/.change the current file (maps.php/maps.tpl) without reloading.
But, my jQuery is only half working. The jQuery does find the value I'm trying to pass, and I've gotten it to load that correct value in the <.d.i.v.> tag with id #append . The only thing I can't seem to do is that take value and actually post it to maps_append.php
Any help will be very appreciated!
Thank you!
PS: I think the change will be something like this:
This needs to be replaced:
$('#append').text(str);
})
.change();
With something like this:
url = "maps_append.php";
$.post( url, { cmd: cmdview, value: str } ,
function( data ) {
var content = $( data );
$( "#result" ).append( content );
}
);
$term_input.val('');
});
EDIT::
My current file is maps.php. I now have it appending maps_append.php to maps.php with this code:
<script>
$('#cmdview').change(function() {
//alert('Handler for .change() called.');
var str = "";
url = "maps_append.php";
url = "maps_append.php";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$('#append').load(url);
})
.change();
</script>
I just need to post the value of the select tag now!
Closer still... please see this edit:
<script>
$('#cmdview').change(function() {
//alert('Handler for .change() called.');
var str = "";
url = "maps_append.php";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$.post( url, { str: "$cmdOn" } ,
function( data ) {
var content = $( data );
$('#append').load(url);
})
.change();
});
</script>
Now the maps_append.php page only appends to maps.php when I change the value of the select tag. I only need to include the value of the select tag when maps_append.php appears now.
I don't quite understand the details of what you are doing here -- all the code looks fine but the plan seems a little strange.
Typically you don't have a program change the source. Instead you would have code store data in a database and the code would be driven by the database to produce different output.
Maybe this is what you want to do with the content -- store it in a database and have a page that displays it.
To load content via jQuery use the following
function loadContent(elementSelector, sourceUrl) {
$(""+elementSelector+"").load("http://yoursite.com/"+sourceURL+"");
}
See this link: http://frinity.blogspot.com/2008/06/load-remote-content-into-div-element.html
I would like to make it that when a button is clicked a certain values in a drop down menu appears later on in the same document.
For example if there was a button called Honda and it is clicked it would change the content in a drop down menu to the model details of the car.
How is it possible to do this?
CONTEXT: Webpage on a PHP enabled server
Thanks in advance!
I suggest the simplest solution is a JavaScript. Seems overload to use a framework for such a simple task:
<html>
<head><title>JS example</title></head>
<body>
<script type="text/javascript"><!--
//
var opt_one = new Array('blue', 'green', 'red');
var opt_two = new Array('plaid', 'paisley', 'stripes');
//
function updateTarget() {
var f = document.myform;
var which_r = null;
if (f) {
// first option selected? ("One")
if (f.trigger.value == '1') {
which_r = opt_one;
// ...or, second option selected? ("Two")
} else if (f.trigger.value == '2') {
which_r = opt_two;
// no known option, hide the secondary popup
} else {
f.target.style.display = 'none';
}
// did we find secondary options for the selection?
if (which_r) {
// reset/clear the target pop-up
f.target.innerHTML = '';
// add each option
for (var opt in which_r) {
f.target.innerHTML += '<option>' + which_r[opt] + '</option>';
}
// display the secondary pop-up
f.target.style.display = 'inline';
}
}
} // updateTarget()
//-->
</script>
<form name="myform" action="#">
<select name="trigger" onchange="updateTarget();">
<option>Select one...</option>
<option>-</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<select name="target" style="display:none;">
</select>
</form>
</body>
</html>
You could do this using jquery, with one PHP backend script to populate the values of the select box based on the button you click.
Some simple HTML to start with:
<form action="script.php">
<button id="Honda" onClick="loadModelsForMake('Honda');">Honda</button>
<button id="Toyota" onClick="loadModelsForMake('Toyota');">Toyota</button>
<select name="models" id="models">
<option value="">Please Select A Make</option>
</select>
</form>
Then you'd need a PHP script set up to give you the appropriate list of values given the make selected. Best to do this on the back-end so you don't hardcode things in your javascript code. Make a file called models.php. It will look for the "make" variable defined in the query string and return a JSON array of models for that make. If you want you can hook this up to a database of models for makes so you're not hard coding things:
<?php
$models = array();
if ($_GET['make'] == 'Toyota') {
models[] = array(id: 0, name: 'Matrix'});
models[] = array(id: 1, name: 'Yaris'});
} else if ($_GET['make'] == 'Honda') {
models[] = array(id: 0, name: 'Civic'});
models[] = array(id: 1, name: 'Pilot'});
}
echo json_encode($models);
?>
Lastly you need the JQuery to hook it all together. Add this script block to your page:
<script type="text/javascript" charset="utf-8">
function loadModelsForMake(carMake) {
$.getJSON("/models.php", {make: carMake, ajax: 'true'}, function(json){
var options = '';
for (var i = 0; i < json.length; i++) {
options += '<option value="' + json[i].id+ '">' + json[i].name + '</option>';
}
$("models").html(options);
})
}
</script>
Of course make sure you include the base jQuery script in your page ;)
You would need to use AJAX and jQuery has functions built in that can make this simpler.
As for the button itself, you would use onclick to start the request.
<input type="button" onclick="carRequest('honda');" />