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);">
Related
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!
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']);
}
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 don't know anything about JavaScript unfortunately so forgive me for asking such an amateur question.
I've got a form with select boxes and a button next each one. I've disabled the button, and I want for the button to be enabled when a user selects something in the check box.
This is what I've got at the moment to product the select box and the disabled button.
<td style="width:125px;"><strong>Processor:</strong></td>
<td style="width:420px;">
<select class="custom-pc" name="processor">
<option value=""></option>
<?php
$processor_query = #mysql_query("SELECT * FROM custom_pc_processor");
while ($p_q = mysql_fetch_array($processor_query)) {
$id = $p_q['id'];
$name = $p_q['name'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
?>
</select>
<input name="processor_details" type="button" value="Details" disabled="disabled" />
</td>
The simplest solution is to add an onchange event handler to the select element. For example (assuming your elements are in a form):
<select onchange="this.form['processor_details'].disabled = false;" ...(rest of code)
I suggest jQuery for best browser support (and ease of coding):
$(function() {
$('.custom-pc').change(function() {
$(this).next('input').removeAttr('disabled');
});
});
You can use like this
<td style="width:125px;"><strong>Processor:</strong></td>
<td style="width:420px;">
<select class="custom-pc" id="processor" name="processor" onChange='UpdateButton()">
<option value=""></option>
<?php
$processor_query = #mysql_query("SELECT * FROM custom_pc_processor");
while ($p_q = mysql_fetch_array($processor_query)) {
$id = $p_q['id'];
$name = $p_q['name'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
?>
</select>
<input id="processor_details" name="processor_details" type="button" value="Details" disabled="disabled" />
</td>
...
<
script>
function UpdateButton()
{
var bDisable;
if (document.getElementById ("processor").value == '') // change the condition if required.
bDisable = true;
else
bDisable = false;
document.getElementById ("processor_details").disabled = bDisable;
}
</script>
Untested, but off the top of my head this should work.
// Give your form a name, I'm using myform.
// Add an event to the onchange of the <select>
document.myform.processor.onchange = function() {
// Enable the button
document.myform.processor_details.disabled = false;
};
You need to put one function onChange event in select box.
<select class="custom-pc" name="processor" onChange="return getEnable(this.form);">
<option value=""></option>
<?php
$processor_query = #mysql_query("SELECT * FROM custom_pc_processor");
while ($p_q = mysql_fetch_array($processor_query)) {
$id = $p_q['id'];
$name = $p_q['name'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
?>
</select>
//Javascript function look like below.
function getEnable(frm){
frm.processor_details.disabled = false;
return true;
}
Thanks.
Without jQuery, the following code block at the bottom of your HTML BODY should suffice.
<script type="text/javascript">
var ddl = document.getElementsByName('processor')[0];
ddl.onchange = function () {
document.getElementsByName('processor_details')[0].disabled = !this.value;
};
</script>
If you're going to do a lot of web development in your career, you really need to learn JavaScript and the DOM. W3Schools will help, especially this chapter.
I do recommend learning jQuery though. It will make your life 1000 times easier and also make you more attractive to the gender of your choosing.
try this ( with jQuery v 1.6 )
$('select').change(function() {
var op =$(this).val();
if(op !=''){
$('input[name="processor_details"]').prop('disabled',false);
}else{
$('input[name="processor_details"]').prop('disabled', true);
}
});
DEMO
Use jQuery
take something like
$( ".custom-pc" ) . change(function(){
if ( selid( "#idselect" ) )
{
$( "#button" ) . attr ( "enabled", "enabled" );
}
})
selid - function, which show id of selected element.
function selid( name ) //get selected id of select element, or false
{
var id = false;
$("#"+name+" option:selected").each(function () {
id = $(this).val() ;
});
return id;
};
Sorry, maybe it can be rewritten to be more effective.
PS. Also - to mix PHP & JS, in SO question, is not very good idea :) Am sure :)
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');" />