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 :)
Related
I have a <select> with only one option, i want to get the rest of the options from a database using PHP and then populate said <select> with the PHP result using AJAX.
Unfortunately my code is not working, im not surprised as im new to both AJAX and jQuery but i dont get any errors to guide myself through the issue.
The PHP works as expected because its used in another part of the site and i have no issues with it so my error must be in the AJAX (no big surprise here).
Below my HTML:
<select class="custom-select my-1 mr-sm-2" id="producto" name="producto" required>
<option disabled selected value>Elegir...</option>
</select>
Below my AJAX code:
<script type="text/javascript">
$(document).ready(function() {
$("#producto").click(function() {
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
$("#producto").append(data);
}
});
});
});
</script>
Below my PHP code:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
?>
As always any kind of help is greatly appreacited and thanks for your time.
IMPORTANT EDIT
<select> has a duplicated id, perhaps i should i have stated this from the start as i know think thats whats causing my issue.
The fact is that in this <form> the selects are created dynamically on user request. They click on Add product and a new select with the products avaiable is created, i know the id/name of said input must have [ ] (id="producto[]") for it to be converted into an array but i dont know how to make the AJAX deal with this dynamically created reapeated selects issue. I apologise for this belated aclaration i realise now it is of the utmost importance.
You have to edit your response from this:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
?>
To this:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
$response = '';
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
$response .= '<option value="' .$titulo . '">' . $titulo . '</option>'; //Concatenate your response
}
echo $response;
?>
But i suggest to use JSON to get a response and parse it on client side.
You can do this by pushing all values in to response array and use json_encode(). At the end you get straight response from the server with just a values, and append thous values whatever you need on client side.
Update
Also you append data to your existing select options. You can just add thous by editing this:
<script type="text/javascript">
$(document).ready(function() {
$("select#producto").focus(function() { //Change to on Focus event
$.ajax({
url: 'fetch_lista_productos_compra.php',
success: function(data) {
$("select#producto").html(data); //Change all html inside the select tag
}
});
});
});
</script>
Test result:
$('select#options').focus(function(){
alert("Hello this is a select trigger");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="options">
<option value="test">Test</option>
</select>
Please don't construct your html on the server, try to just send the raw data and then construct the html client-side, it's better that way and it leaves room for changing the view later without much coupling.
That said, instead of doing:
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
just do
$rows = [];
while ($row = mysqli_fetch_assoc($sql_query)) {
$rows[] = $row;
}
//this is your best bet when sending data from PHP to JS,
//it sends the rows as JSON-like string,
//which you'll parse to an array in the client
echo json_encode($rows);
then in the client
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: (data /*json-like string*/) => {
const dataAsArray = JSON.parse(data);
$.each(dataAsArray, (index, row) => {
//now HERE you construct your html structure, which is so much easier using jQuery
let option = $('<option>');
option.val(row.titulo).text(row.titulo);
$("#producto").append(option);
});
}
});
Regarding your edit about several selects
I don't have access to your server of course so I'm using a mock service that returns JSON. IDs are dynamically generated and all data loading occurs asynchronously after you click on the button.
Try using your url and modify the success function according to your html.
$(document).ready(function() {
$('#add').click(() => {
//how many so far...?
let selectCount = $('select.producto').length;
const select = $('<select class="producto">');
select.attr('id', `producto${selectCount + 1}`);
//then we fetch from the server and populate select
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'get',
success: function(data) {
data.forEach((d) => {
const option = $('<option>');
option.val(d.id).text(d.title);
select.append(option);
});
}
});
document.body.appendChild(select[0]);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='add'>Add product</button><br>
<!--<select class="custom-select my-1 mr-sm-2" id="producto" name="producto" required>
<option disabled selected value>Elegir...</option>
</select>-->
HIH
As it turns out the code in the question was actually working properly, the problem was not the code itself but the fact that, as i stated (sadly on a later edit and not right from the start) in the question, there where more than one <select> using the same id, therefore everytime the AJAX was executed the result was appended to the first <select> only, and it was appended over and over again everytime i clicked it, my solution was unifiying both the AJAX that populated the <select> and the jQuery that created the said dynamic <select>'s all in one script thus solving all of my issues at once.
Below my jQuery/AJAX code:
<script type="text/javascript">
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 0;
$(add_button).click(function(e) {
e.preventDefault();
$.ajax({
url: '/testground/php/fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
if(x < max_fields) {
x++;
var html = '';
html += '<div class="form-group row" id="inputFormRow" style="margin-bottom: 0px;">';
html += '<label class="col-3 col-form-label font-weight-bold">Producto</label>';
html += '<div class="col-7">';
html += '<select class="custom-select my-1 mr-sm-2" id="producto" name="producto[]" required>';
html += '<option disabled selected value>Elegir...</option>';
html += data;
html += '</select>';
html += '</div>';
html += '<div class="col-1 my-auto" style="padding: 0px 0px 0px 0px;">';
html += '<button id="removeRow" type="button" class="btn btn-danger">X</button>';
html += '</div>';
html += '</div>';
$(wrapper).append(html);
}
}
});
});
$(document).on('click', '#removeRow', function () {
$(this).closest('#inputFormRow').remove(); x--;
});
});
</script>
I want to thank everyone that took the time to help me out with this Swati, Serghei Leonenco and Scaramouche, this community is truly amazing.
<script type="text/javascript">
$(document).ready(function() {
$("#producto").change(function() {
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
console.log(data)
// $("#producto").append(data);
}
});
});
});
</script>`enter code here`
try run this and check in your console that weather you are receiving the data from your php or not.
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!
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);">
How I would access this url index.php/backend/categories/get_categories/$id within a <select> dropdown onChange ?
I mean, if I will go to index.php/backend/categories/get_categories/1, it will output a table with all categories under component id 1.
What I want, is once i select an option from a dropdown list, i want it to submit and redirect to the same url, but with a specific ID from <option val="$id"> ?
To generate a dropdown list with CodeIgniter FORM helper:
<?php
echo form_open('backend/categories/get_categories');
$selectComponentData = array(0 => '-- '.lang('SELECT_COMPONENTS').' --');
$selectComponentJs = 'onChange="this.form.submit()" id="selectCatsByComponent"';
foreach($selectComponents as $option){
$selectComponentData[$option->id] = $option->name;
}
echo form_dropdown('selectCatsByComponent', $selectComponentData, 0, $selectComponentJs);
echo form_close();
?>
And output HTML is:
<form accept-charset="utf-8" method="post" action="http://127.0.0.1/backend/web/index.php/backend/categories/get_categories">
<select id="selectCatsByComponent" onchange="this.form.submit()" name="selectCatsByComponent">
<option selected="selected" value="0">-- Choose a component --</option>
<option value="1">E-commerce</option>
<option value="2">Content</option>
</select>
</form>
How to make it possible ?
if I dont get you wrong, You are asking something like this;
In controller;
public function get_categories()
{
if(isset($_POST) && !empty($_POST())
{
$id = $this->input->post('selectCatsByComponent');
// bla bla bla
$data['id'] = $id;
$this->load->view('whatever/whatever',$data);
}
else
{
//Your normal page before posting
}
}
Now you can access the id value in view like this
if(isset($id)) // if there is a $id loaded
{
// Your view accoring to $id
}
Note: I did not have an test environment while I was writing this code. So The code is not complate and there might be some mistakes
You can use ajax with jquery onchange function, see the below example:
$("#bussiness").live('change',function(){
var bus_id=$(this).val();
$.ajax({
url : "<?php echo base_url(); ?>setting/set_session/"+bus_id,
success:function(res) {
document.getElementById('output').HTML = res;
}
});
});
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');" />