I am trying to disable a submit button when one or more of the selectors (generated dynamically) shown in the picture are empty..
I tried the following jQuery code:
<script>
var $submit = $("input[name=store_values]");
$(".ownlevelselect").each(function(){
if($(".ownlevelselect:empty").length>0){
$submit.attr("disabled","disabled");
}else {
$submit.removeAttr("disabled");
}
});
</script>
and these are the relevant parts of my form:
echo "<select class='ownlevelselect' id='ownlevelselect' name='level-".$compi['Competence_ID']."' >";
and the input buttons:
echo "<input type='submit' name='submit_values' value='Save'>";
echo "<input type='submit' name='store_values' value='Store'></form>";
The one I want to disable is the one with name='store_values'
There's something ambiguous in your question, do you mean empty like DOM empty (selects that contains no elements) or empty like selects with an empty value selected ?
If you mean empty like emtpy value, you can try this, handling change event like Shadow Wizard said:
$('document').ready(function(){
var submitButton = $('input[name="store_values"]');
/* Called to disable button on page load, done here but probably possible server-side */
checkValues()
/* Called on change event on dropdowns */
$('select.ownlevelselect').on('change',function(){
checkValues();
});
function checkValues(){
/* Disable button if found an empty <select> (mean, no <option> inside), or a select with an empty value selected */
submitButton.prop('disabled',$(".ownlevelselect > option:selected[value=''],.ownlevelselect:empty").length > 0);
}
});
If you mean empty like "Dom empty" (no option defined inside the select), you can try this (you can place it into a function and call it each time you dynamically add an element)
$('document').ready(function(){
var submitButton = $('input[name="store_values"]');
submitButton.prop('disabled',$(".ownlevelselect:empty").length > 0);
});
EDIT
Be carefull about your IDs, I don't have any relevant part of code to be sure, but you seem to reuse same ID for your selects, which is a bad idea :)
EDIT2
Here's a fiddle, so as you can see if I missed something:
http://jsfiddle.net/d8rb9/
you can use the event onBlur for each select to trigger a function that tests if all the other select are not empty, and then activate the submit button if so.
here is an exemple:
The select Tag :
<select class="ownLevelSelect" onBlur="checkSelects()">
<option></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
The Javascript function:
<script>
function checkSelects(){
// integer to count the number of select with a correct value
var nonEmpty = 0;
// loop on all the select in the page with the class attribute : "ownLevelSelect"
$('.ownLevelSelect').each(function(){
if($(this).val()) {
nonEmpty++;
}
});
//desactivate the submit button if the number of selects in the page <> nonEmpty
($('.ownLevelSelect').length == nonEmpty)? $('#theSubmit').removeAttr("disabled") : $('#theSubmit').attr("disabled","disabled");
}
</script>
and maybe you need to call this function on page load so the button is disabled by default if one of the fields are empty
<script>
$(document).ready(function() {
checkSelects();
});
</script>
Note :
The ID attribut must be unique on the page, so in your code change this :
<select class='ownlevelselect' id='ownlevelselect' name='level-".$compi['Competence_ID']."' >";
By this :
<select class='ownlevelselect' id='ownlevelselect-".$compi['Competence_ID']."' name='level-".$compi['Competence_ID']."' >";
I hope this helped.
Related
I am getting a SelectChanged is not defined message when using the following code. For the life of me, I cant figure why since I have used this before:
jQuery
jQuery("#name").on("change", function() {
alert(this.value);
});
dropdown
echo('<td class="table-font"><select id="name" onchange="SelectChanged(this)">');
foreach($Staff_On_Duty as $person){
$sf_name_option=$person->Staff_First_Name;
$sl_name_option=$person->Staff_Last_Name;
echo("<option value = $sf_name_option $sl_name_option");
if (($sf_name_option == $sf_name) && ($sl_name_option == $sl_name)) echo (" selected");
echo(">$sf_name_option $sl_name_option</option>");
}
echo("</select></td>");
Yes I am aware that the above method of showing the menu isn't the best, I am working on getting the functionality I need, then can make it better through separating the HTML and PHP etc
You're trying to do the same thing twice.
You can call a function inline using onchange=function() or you can add a JQuery event listener using $(elem).on('change', function() {}).
Your code is actually working (using the jquery event listener) but you are also getting an error from the attempt to run an inline function. The inline function is not defined (i.e. when the select is changed it tries to find a function called SelectChanged but as it has not been defined you are getting an error).
The example below shows both methods functioning.
// Add a jquery event listener to the element with the id name, listening for any change
jQuery("#name").on("change", function() {
// Print the value of the element
console.log("From JQuery function: " + this.value);
});
// Function that can be called inline using onchange = "SelectChanged(this)"
function SelectChanged(el) {
// Print the value of the inline element
console.log("SelectChanged function: " + el.value);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td class="table-font">
<select id="name" onchange="SelectChanged(this)">
<option value="Firstname Surname 1" selected>Firstname Surname 1</option>
<option value="Firstname Surname 2">Firstname Surname 2</option>
</select>
</td>
jQuery("#name").change("#name")
function SelectChanged() {
alert(this.value);
}
I have a form which sends information with post method to another page. In the form I have a select box with three options, for example:
<select name="slctstate" id="slctstate">
<option value="0">aaaaa</option>
<option value="1">bbbbb</option>
<option value="2">ccccc</option>
</select>
In another page, I read the selected item with $_POST['slctstate'], but I want to read all options (key & value) in the select tag.
Can I do this?
First use a jquery function which stores all the options in a string
$(document).ready(function()
{
var myoption = '';
$('#drop_down option').each(function()
{
myoption = myoption + ',' + ($(this).val());
});
$('#hidden_text').val(myoption);
}
);
in the html use a hidden field
<input type="hidden" id="hidden_text" name="hidden_text"/>
WHen you will submit the form, catch this value with a list of options separated by (,);
On the action page, you can split the value using php explode() function
Check the fiddle
http://jsfiddle.net/1u9x5nbq/3/
No you can't without a work-around. The only value gets passed is the selected value. If you want to know all values you can use a work-around in javascript e.g.:
<select name="slctstate" id="slctstate">
<option value="0">aaaaa</option>
<option value="1">bbbbb</option>
<option value="2">ccccc</option>
</select>
//Include JQuery
<script>
$(function()
{
$('#slctstate option').each(function()
{
$('#slctstate').after('<input type="text" value="'+$(this).text()+'" name="slctstateOptions['+$(this).val()+']" style="display:none;" />');
//Where val() is the key and text() is the value.
});
});
</script>
Then you can access the values by using $_POST['slctstateOptions'].
No, you can't do that from the form. When you do submit, you send only selected value(s).
No,
The only value that is "selected" will be POSTed on Submit.
I'm using Select2 3.4.5 for create select boxes,
I use this code for creatre a Multi-Value Select Boxe and everything is fine.
<select id="e1" name="mydata" multiple>
<option value="D1">Data1</option>
<option value="D2">Data2</option>
<option value="D3">Data3</option>
</select>
...
<script>
$("#e1").select2();
</script>
For get multiple selected values of select box in php I have to modify name="mydata" by name="mydata[]", and in PHP I get values by this code:
<?php
foreach ($_POST['mydata'] as $names) {
print "You are selected $names<br/>";
}
?>
But my question: How can I send selected values of select box to PHP as string to recover in php like this : 'D1,D2,D3' , and thanks.
Edit:
I want to send the data as string, not receive it as an array then
change it as string
Server-side with PHP
Ideally you would do this with PHP once the value is sent. To convert the selected items just want to implode the array
$names=implode(',', $_POST['mydata']);
Where $_POST['mydata'] is an array
[0]=>'D1',
[1]=>'D2',
[2]=>'D3'
implode(',', $_POST['mydata']) would be 'D1,D2,D3'
Client-side with jQuery
Your title says "send selected values of select box to PHP as string". You would do that in JS by catching the submit event of the form and using .join() to change the value of that field.
$('#formid').on('submit', function(){
$('#e1').val($('#e1').val().join(','));
});
Your form (not given) would need an id <form id="formid" ...>
If you want a client-side solution, try getting the val() and calling join():
$('#e1').val().join()
http://jsfiddle.net/gwgLV/
You can do it with javascript.
<select id="e1" name="mydata" multiple>
<option value="D1">Data1</option>
<option value="D2">Data2</option>
<option value="D3">Data3</option>
</select>
<button id="but" onclick="now()">Show selected values</button>
javascript code
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
function now(){
var el = document.getElementsByTagName('select')[0];
var x = getSelectValues(el);
alert(x);
}
Demo here
Instead of alert store in a variable and send it along with the rest of the form data. Or you can use join (as mentioned in other answers ) to send it over post to php.
I have a drop down list (ddlAccount) which i can choose an item from it and do a db query in test.php to retrieve corresponding data, then output an input element with the returned data.
This is my javascript code:
function load1(){
$('#divAccountNum').load('test.php?accountInfo=' + document.getElementById('ddlAccount').value , '' ,function() {
alert('Load was performed.')});
}
load1 function called when i change the dropdown list items, and it takes the value of the selected option and sends it to test.php in a parameter called "accountInfo".
my html:
<select name="ddlAccount" id="ddlAccount" onchange="load1();">
<option value="1"> Account1</option>
<option value="2"> Account2</option>
<option value="3"> Account3</option>
</select>
<div id="divAccountNum" >
</div>
And test.php :
if($_GET['accountInfo'])
{
$account = $accountDAO->load($_GET['accountInfo']); //mysql query
//print an input holding account number as its value
echo "<input type='text' name='txtAccountNum' id='txtAccountNum' value='".$account->accountnumber."'/>";
}
The problem is that nothing happened when i choose an option (nothing appear in div (divAccountNum))
Any suggestions? Thanks in advance.
Edit:
I used #thecodeparadox 's bit of code and it works and i found a solution for the problem that i mentioned in the comments below which is that when choosing one item from the dropdown list it shows the value in input element and loads the form again. The solution is in:
jQuery Ajax returns the whole page
So my jquery code now looks like:
$(document).ready(function(){
$('#ddlAccount').on('change', function() {
$.get('testJquery.php?accountInfo=' + $(this).val(), function(accountNum) {
//console.log(accountNum);
$('input#txtAccountNum').val(accountNum);
});
});
And testJquery.php :
if($_GET['accountInfo'])
{
$account = $accountDAO->load($_GET['accountInfo']);
$accountNum = $account->accountnumber;
echo $accountNum;
}
And at last i added input element in divAccountNum which has id="txtAccountNum"
Though you don't give enough info about your problem, but you can try this:
function load1(){
$('#ddlAccount').on('change', function() {
$.get('test.php?accountInfo=' + $(this).val(), function(response) {
$('div#divAccountNum').html(response);
}, 'html');
});
}
NOTE:
$('#ddlAccount').on('change', fires when dropdown change
$.get('test.php?accountInfo=' + $(this).val().. send a get(ajax) request to test.php with value selected from drop down
parameter response with in $.get() second parameter callback function is the response from the server
'html' as third parameter of $.get() for data type you return, as you return a html so it is html.
for more info read:
change()
$.get()
To get selected option value from select input use:
$('#ddlAccount option:selected').val()
I am having trouble trying to get a value from a drop-down list and multiplying the value by a number in the 'ticket' table. I've been trying to implement this calculation in both PHP and javascript but having no luck :(
Here is the form (which is returned to the homepage by AJAX):
$pcSearch = $_POST['postcodeSearch'];
$postCodeSQL = "SELECT * FROM ticket WHERE locationID IN (SELECT locationID FROM location WHERE postCode LIKE '$pcSearch') ";
$postCoderesult = mysql_query($postCodeSQL) or die(mysql_error());
while ($pcRow = mysql_fetch_assoc($postCoderesult)) {
$venue = $pcRow['venue'];
$ticketPrice = $pcRow['tPrice'];
$date = $pcRow['date'];
$time= $pcRow['time'];
echo "<tr>\n";
echo "<td>$venue</td>\n";
echo "<td>£$ticketPrice</td>\n";
echo "<td><form id=\"quantity\" method=\"post\" name=\"ticketQuantity\">
<select name =\"showQuantity\" id=\"showQuantity\" class =\"showQuantity\" >
<option value=\"1\">1</option>
<option value=\"2\">2</option>
<option value=\"3\">3</option>
<option value=\"4\">4</option>
<option value=\"5\">5</option>
</select>
</form>
</td>\n";
echo "<td>$date</td>\n";
echo "<td>$time</td>\n";
echo "<td><form name=\"buyTicket\" class=\"buyTicket\" id=\"buyTicket\" >
<input type= \"button\" id= \"buyMe\" class= \"buyMe\" value= \"Buy\" name=\"buyMe\">
</form>
</td>\n";
echo "</tr>\n";
}
Basically, what I wanting to do is when a user clicks and choose the quantity of tickets they want i.e. 3, this number will be multiplied by the price of the ticket ('tPrice'). Is there a way of getting both these values and multiplying them together in PHP?
I've tried adding jQuery to listen for the button click function but to no avail...I even tried debugging it but for some strange reason it won't output the alert:
$(document).ready(function() {
$(".buyMe").click(function() {
alert('click');
});
});
However if I were to use jQuery, how would I even get the value of 'tPrice' from the form?
Thanks very much for any help :)
The first thing i would do is add a class to the ticket price td :
echo "<td class=\"ticketPrice\">£$ticketPrice</td>\n";
What that does it make it a lot easier to get the price using jQuery.
So now .. you can do this :
$(".buyMe").click(function() {
var priceForOne = $(this).siblings('.ticketPrice').text().substr(1);
});
Infact as you have access to the source of the HTML a better way would probably using data() :
echo '<input type="button" class="buyMe" value="Buy" data-ticket-price="'.$ticketPrice.'"/>';
then you can change your click to be :
$(".buyMe").click(function() {
var priceForOne = $(this).data('ticketPrice');
});
A couple of other points ..
remove the id attribute from here :
<input type= \"button\" id= \"buyMe\" class= \"buyMe\" value= \"Buy\" name=\"buyMe\">
there is no need for a form around the select list as its doing nothing ... similarly the form around the button is doing nothing either !
Updated
The click method won't work for DOM elements added after the document has been loaded (ie via AJAX) ... you need to use the on() method :
$(document).on('click','.buyMe',function() {
// handle the click here
});
the $(document) above needs to be a parent element of the buyMe element and present on the DOM at load, in your case you could replace $(document) with $('#idOfYourTable')
Docs for data() and Docs for on()
You're referencing a non-existent class name instead of the id. Change .buyme to #buyme
$(document).ready(function() {
$("#buyMe").click(function() {
alert('click');
});
});
Edit missed that the class is on there too. However since you're just referencing a single element you should use the ID anyway.