I am working on PHP. I have three dynamic dropdown boxes. On the basis of first selected value I change the content of second select box and same case for the third. I have achieved this functionality through javascript. The problem I am having is my code works perfectly on localhost but when I upload the code on the online server the page keeps on reloading. Let me first share my code so that you can have an idea of what I am talking about
javascript
<script>
var valnew = <?php echo $cat3; ?> ;
function reload() {
var val = form.cat.options[form.cat.options.selectedIndex].value;
var text = form.cat.options[form.cat.options.selectedIndex].text;
self.location = 'douglas-college.php?cat=' + val + '&text=' + text
}
function reload3(form) {
var val = form.cat.options[form.cat.options.selectedIndex].value;
val2 = form.subcat.options[form.subcat.options.selectedIndex].value;
self.location = 'douglas-college.php?cat=' + val + '&cat3=' + val2;
}
function reload4(form) {
var val3 = form.subcat3.options[form.subcat3.options.selectedIndex].value;
var text = form.subcat3.options[form.subcat3.options.selectedIndex].text;
self.location = 'course-title.php?inst_id=' + val3 + '&coursecode=' + valnew;
}
</script>
<?php
$query1 = mysql_query("SELECT * FROM course");
echo "<select name='cat' class='input-large form-control' onchange=\"reload(this.form)\">";
if (!isset($_GET['cat'])) {
echo '<option>Select one</option>';
while ($row = mysql_fetch_array($query1)) {
echo '<option value="' . $row['courseID'] . '">' . $row['courseName'] . '</option>';
}
} else {
while ($row = mysql_fetch_array($query1)) {
echo '<option value="' . $row['courseID'] . '">' . $row['courseName'] . '</option>';
}
}
echo "</select>";
?>
I have added only one selectbox php code right now. I can share the whole code upon request. I have checked the page by using only one dropdown but still page keeps on refreshing. Means the page is keep on reloading again and again
The real problem is that in :
http://smithdeveloper.com/test/js/sitefunction.js
$('select').change(function() {
$('option').css('background', 'white');
$('option:selected').css('background', '#ff87c3');
}).change();
U trigger .change() on all select elements.
So thats why onchange events are called immediately after page load.
So every time page loads u call change event and listen to change event and fire reload() function
first ditch the inline onchange="" events inside select tags..
Than remove your script from begining of the file and save this in file that you include in the end of the page, sitefunction.js inside document.ready hook.
Here is mine jsfiddle and I changed your functions a bit..
$('[name=cat]').on('change', function(){
var val1 = form.cat.options[form.cat.options.selectedIndex].value;
var txt1 = form.cat.options[form.cat.options.selectedIndex].text;
self.location = 'http://smithdeveloper.com/test/douglas-college.php?cat=' + val1 + '&text=' + txt1
});
$('[name=subcat]').on('change', function(form) {
var val2 = form.cat.options[form.cat.options.selectedIndex].value;
var txt3= form.subcat.options[form.subcat.options.selectedIndex].value;
self.location = 'http://smithdeveloper.com/test/douglas-college.php?cat=' + val2 + '&cat3=' + txt3;
});
$('[name=subcat3]').on('change', function(form) {
var val3 = form.subcat3.options[form.subcat3.options.selectedIndex].value;
var text = form.subcat3.options[form.subcat3.options.selectedIndex].text;
self.location = 'course-title.php?inst_id=' + val3 + '&coursecode=' + valnew;
});
http://jsfiddle.net/mkdizajn/wLz2g3sw/
hth, cheers, k
Related
Here is a select list built using PHP, MariaDB, and HTML:
echo "<select name='companylist' id='companylist' size='86' value='' tabindex='1' >";
echo "<option value=''></option>";
echo "<option value='0-Create a New Company'>0-Create a New Company</option>";
foreach ($companyResult as $company) {
echo "<option id='".$company['Company_Key']."'
value='".$company['Company_Key']."'>".$company['Company_Names']."</option>";
}
echo "</select>";
It builds a dropdown list that is appropriate for my application.
Next, I built this testing script to find out if I was on the right track in the use of RegExp to filter the dropdown select list dynamically, and it works well, for its purpose. I only built it because the list following it is giving me fits.
echo "<script>";
echo "$('#companylist option').each(function() {
var Val = this.text;
var Filter='W';
var CompRegex = new RegExp('^'+Filter);
if(CompRegex.test(Val)){
console.log('RegExp with Filter has found the following Val starting with this
Filter: '+Filter);
console.log('Val = ' + Val);
}
})";
echo "</script>";
This above gives me the following console output:
RegExp with Filter has found the following Val starting with this Filter: W
Val = Welch Tile
RegExp with Filter has found the following Val starting with this Filter: W
Val = West Michigan Molding
RegExp with Filter has found the following Val starting with this Filter: W
Val = WL Molding of MI
This is a good start.
echo "<script>";
echo " $('#companylist')";
echo " .editableSelect()";
echo " .on('select.editable-select', function (e, li) {
console.log('value = ' + document.getElementById('companylist').value);
console.log('li.val() = '+li.val());
getCustomer_Names(li.val());
getTool_Numbers(li.val());
getPart_Name(li.val());
newCompany_Name();
})";
echo "</script>";
This above script loads other menus, as expected, once the user selects an item.
The next script here simply will not let me get the option text that the user sees in the list. I have 5 days into this, because I am new to JQuery and not a master of Javascript either, but I do read all kinds of sites for help, including reference guides, and the support boards (thank you for this one!), but I would like a happy ending soon. Any help, as stated, would be very appreciated.
echo "<script>";
echo " $('#companylist')";
echo " .editableSelect()";
echo " .on('input.editable-select', function () {
$(this).each(function() {
var Val = this.text;
var Filter = this.value;
var CompRegExp = new RegExp('^'+Filter);
console.log('Val = '+Val);
console.log('Filter = '+Filter);
console.log('CompRegExp = '+CompRegExp);
if(CompRegExp.test(Val)){
console.log('RegExp with Filter has found the following Val starting with this
Filter: '+Filter);
console.log('Val = ' + Val);
}
else {
// remove from select list
}
});
});";
echo "</script>";
This above script gives me
Val = undefined
Filter = a
CompRegExp = /^a/
It is the "Val = undefined" that is my undoing.
I also took a long-view of this problem and wrote a jQuery/JavaScript program that clears the dropdown list and then recreates the options by having a PHP program re-query the database to get the values that match a SQL LIKE 'Input%' which I will include to show you the depth of effort here. The problem here is that I could not get the dropdown menu to stay open even though I issued .editableSelect('show'); as instructed in the editableSelect git website to open the dropdown menu and show the modified list, although, if I clicked in the field and moved the cursor around, it would pop the menu open with the values that matched the return from MariaDB. It follows:
echo "<script>
function getCompany_Names(comp_val)
{
if(document.getElementById('companylist').value.substring(0,8) != '0-Create'){
$('#companylist').editableSelect('clear');
var xhttp;
if (comp_val === null || comp_val === '' ) {
$('#companylist').editableSelect('add', '<option value=></option>');
$('#companylist').editableSelect('add', '<option value=0-Create a New Company>0-Create a
New Company</option>');
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var select = $('#companylist');
var c_text = this.responseText;
console.log('comp_ctext = ' + c_text);
c_text = JSON.parse(c_text);
$.each($(c_text),function(key,value){
if (value.compname == 'One or more Company Names are Probably Not Entered.')
{
$('#companylist').editableSelect('add','<option value=' + 'One or more Company
Names are Probably Not Entered.' + '>One or more Company Names are Probably Not
Entered.</option>');
}
else
{
console.log('<option id=\'' + value.compkey + '\' value=\'' + value.compkey + '\'>'
+ value.compname + '</option>');
$('#companylist').editableSelect('add','<option id=\'' + value.compkey + '\'
value=\'' + value.compkey + '\'>' + value.compname + '</option>');
}
}); // end .editableSelect('add',...)
}
};
xhttp.open('GET', 'getCompany_Names.php?q='+comp_val, true);
xhttp.send();
}
}
</script>";
This is all because my patron does not like the default filter behavior of the editableSelect package where it matches what is typed to any values anywhere in the dropdown and wants some dropdowns to come up matching the input to the results from first character onward with something like (exactly like) a regex of /^input_variable/.
Thank you for your time.
R
its not a solution, just easier to ask something..i'll delete more later
i dont understand this syntax: no selector before .on??
.on('input.editable-select', function () {
$(this).each(function() {
i see $(this) that means you have more input?
the problem with these lines:
var Val = this.text;
var Filter = this.value;
what is Val? because this.text is not functional for input? (its the reason Val => undefined)
this.value gives what you type in input
This is WAY more complicated than my core problem actually is. I have posted another question that is just my actual failure. It is at: [https://stackoverflow.com/questions/66801231/the-use-of-https-github-com-indrimuska-jquery-editable-select-for-editable-sel]
I think I have an example of an example page the creator put together and it has a function their I am only just starting to understand, but it is all about adding values to the list. I will study it and post my results on the core issue page. Thank you to all who tried to help. Here's one for brevity.
$MethodLocationFrom =mysql_query("
SELECT DISTINCT Location_From AS 'locationFrom'
FROM trip
");
echo "<form action='confirmation.php' method='post'>";
echo "<select class = 'LocationFrom' size='1' name='locationFrom' id='locationFrom'>";
while($check = mysql_fetch_array($MethodLocationFrom))
{
echo "<option value='" . $check['locationFrom'] . "'>" . $check['locationFrom'] . "</option>";
}
echo"</select>";
$MethodLocationTo =mysql_query("
SELECT DISTINCT Location_To AS 'locationTo'
FROM trip
");
echo "<select class = 'LocationTo' size='1' size='1' name='locationTo' id='locationTo'>";
while($check = mysql_fetch_array($MethodLocationTo))
{
echo "<option value='" . $check['locationTo'] . "'>" . $check['locationTo'] . "</option>";
}
echo"</select>";
Hi guys! I'm making a shuttle reservation system, I'm having trouble with the option boxes, what I want to do is when I select a place from Location from (first option box) that location would automatically be remove in the location where I want to go (second box) How can I do that?
Ok, let me have a go, with a personal twist
assume the result of iteration to be (reduced for brevity)
<select id="locationFrom">
...
<option value="$from">($from)</option>
</select>
<select id="locationTo">
...
<option value="$to">($to)</option>
</select>
I assume the values of each option-set are the same.
let's get dirty with javascript. Mind you, this is long and has no comments, review it, test it and give me feedback if you find an error.
// script.js
(function(){
var selectFrom, selectTo, unsetChild, nextSibling,
onSelect, removeOption, recoverOption,
loadWin, unloadWin;
onSelect = function () {
var idx = this.selectedIndex;
if (idx !== -1) {
if (unsetChild) {recoverOption();}
removeOption(this.options[idx].value);
}
};
removeOption = function (value) {
unsetChild = selectTo.querySelector('[value="'+value+'"]');
nextSibling = unsetChild.nextSibling;
selectTo.removeChild(unsetChild);
};
recoverOption = function () {
nextSibling
? selectTo.insertBefore(unsetChild,nextSibling)
: selectTo.appendChild(unsetChild);
nextSibling = unsetChild = null;
};
loadWin = function () {
selectFrom = document.getElementById('locationFrom');
selectTo = document.getElementById('locationTo');
selectFrom.addEventListener('change',onSelect,false);
};
unloadWin = function () {
selectFrom.removeEventListener('change',onSelect,false);
selectFrom = selectTo = nextSibling = unsetChild = null;
};
window.addEventListener('load',loadWin,false);
window.addEventListener('unload',unloadWin,false);
});
I've worked out a jQuery solution (tested in Google Chrome):
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript">
function jqyHideSelectedOption(objSelect) {
var strIDSeleted = objSelect.id;
var strID2Handle;
if(strIDSeleted == "locationFrom")
{
strID2Handle = "#locationTo";
}
else
{
strID2Handle = "#locationFrom";
}
strIDSeleted = "#" + strIDSeleted;
//
// show all options: ie, restore default settings.
//
jQuery(strIDSeleted + " option").show();
jQuery(strID2Handle + " option").show();
//
// hide some options in the corresponding select:
//
var selectedCity = jQuery(strIDSeleted).val();
if(jQuery(strID2Handle).val() == selectedCity) {
jQuery(strID2Handle).val(null);
}
jQuery(strID2Handle + " option[value='" + selectedCity + "']").each(function() {
jQuery(this).hide();
});
}
</script>
</head>
<body>
<?php
//
//...
//
$MethodLocationFrom = mysql_query("
SELECT DISTINCT Location_From AS 'locationFrom'
FROM trip
");
echo "<form action='confirmation.php' method='post'>";
echo "<select class = 'LocationFrom' size='1' name='locationFrom' id='locationFrom' onchange='jqyHideSelectedOption(this)'>";
while($check = mysql_fetch_array($MethodLocationFrom))
{
echo "<option value='" . $check['locationFrom'] . "'>" . $check['locationFrom'] . "</option>";
}
echo"</select>";
$MethodLocationTo = mysql_query("
SELECT DISTINCT Location_To AS 'locationTo'
FROM trip
");
echo "<select class = 'LocationTo' size='1' size='1' name='locationTo' id='locationTo' onchange='jqyHideSelectedOption(this)'>";
while($check = mysql_fetch_array($MethodLocationTo))
{
echo "<option value='" . $check['locationTo'] . "'>" . $check['locationTo'] . "</option>";
}
echo"</select>";
//
//...
//
?>
</body>
</html>
For the from city #locationFrom select, an onchange='jqyHideSelectedOption(this)' is used.
When a city is selected in this select, we hide this city name in the list of #locationTo select. If we choose another city, the hidden city is again shown in the destination list, so again available for destination selection.
If a destination is chosen, this city will be hidden in the from cities list.
We don't remove any option from the 2 select's, but rather temprarily hide it, as it's useful if another city is selected, and must be present for customer's selection.
I have a number of checkboxes which, when checked invoke the below script to show a chunk of html inside a form using .load:
$('input.article').click(function(){
var bits = $(this).attr('id').split('_');
var id = bits[1];
var article = 'article_' + id + '.html';
$('#form_' + id).load('<?php echo base_url(); ?>assets/html/' + article);
$('#form_' + id).toggle();
$('.submit').show();
});
The forms are dynamically created in the view like so:
<?php for($i = 1; $i <= 8; $i++){ ?>
<div id="form_<?php echo $i; ?>" class="hide">
</div>
<?php } ?>
However, I need the loaded html to be removed whenever the checkbox is unchecked, and that's where I get stuck. Using .toggle()the html is hidden, but it is being submitted anyway. Any idea how to achieve this?
Try this -
$('input.article').click(function(){
var bits = $(this).attr('id').split('_');
var id = bits[1];
var article = 'article_' + id + '.html';
if(this.checked){
$('#form_' + id).load('<?php echo base_url(); ?>assets/html/' + product);
}
else{
$('#form_' + id).empty();
}
$('.submit').show();
});
So add a check to see if it is checked. If it is not, empty its contents and hide it.
var bits = $(this).attr('id').split('_');
var id = bits[1];
if (this.checked) {
//...get content
} else {
$('#form_' + id).empty().hide();
}
Only load the content if the container is empty, and toggle the container based on wether or not the checkbox is checked :
$('input.article').on('change', function(){
var id = $(this).attr('id').split('_')[0],
article = 'article_' + id + '.html',
form = $('#form_' + id);
if (form.is(':empty'))
form.load('<?php echo base_url(); ?>assets/html/' + article);
form.toggle(this.checked);
$('.submit').show();
});
Function for creating elements:
function create_image(){
<?php if(isset($avatar)) : ?>
var brojac = 5;
<?php else: ?>
var brojac = 4;
<?php endif; ?>
var broj_slike = (5 - brojac) + 1,
slike;
for (var i = 0; i < brojac; i++) {
slike += '<label for="image'+ broj_slike +'">Slika ' + broj_slike + '</label><input type="file" name="userfile" id="image' + broj_slike + '" />';
broj_slike++;
};
return slike;
}
Function that inserts elements on the page:
var code = $('#code'),
id = $('input[name=id]').val(),
url = '<?php echo base_url() ?>mali_oglasi/mgl_check_paid';
code.on('focusout', function(){
var code_value = $(this).val();
if(code_value.length != 16 ) {
if ($('p[role=code_msg]').length != 0 ) $('p[role=code_msg]').remove() ;
code.after('<p role=code_msg>Pogrešan kod je unešen.</p>');
} else {
if ($('p[role=code_msg]').length != 0 ) $('p[role=code_msg]').remove() ;
$.post(url, {id : id, code : code_value}, function(data){
if($.trim(data) != 'TRUE'){
code.after('<p role=code_msg>Uneti kod je neispravan.</p>');
} else {
/*This part here put elements on the page*/
code.after('<p role=code_msg>Status malog oglasa je promenjen.</p>')
.after(create_image()).hide();
code.prev().remove();
code.remove();
}
});
}
});
How can I hide new elements?
I haven't seen the entire code but hiding an element is as simple as using the hide method.
$('<div/>').appendTo('#el').hide();
I'm creating and inserting the element into the dom before hiding it - an example that should resemble yours, if I understood correctly. (it is a bad practice, though, to insert an element in the dom to hide it immediately afterwards - it'd be better to insert it in the dom already hidden - it'd prevent an unnecessary reflow).
With this: $(jqueryelement).hide()
I would hide it before the element gets added to the DOM.
$('<div>').css({"display": "none"}).appendTo(elementInDOM);
OR
$(elementInDOM).append(
$('<div>').css({"display": "none"})
);
I'm sure there are plenty of other ways!
I have a page that generates forms depending on user choice. I want to know if there is a way to convert the form into plain text? Ex. The form has 4 fields, each has a label. I would like to take all the labels/fields and print them to the user as follows:
label1 field1
label2 field2
label3 field3
label4 field4
Is there a way to do so?
You can use jQuery to generate basic output, for example:
var texts = [];
$("form label").each(function() {
var oLabel = $(this);
var oInput = oLabel.next();
texts.push(oLabel.text() + " - " + oInput.val());
});
var plainText = texts.join("<br />");
$("#Output").html(plainText);
This will iterate over all the form labels, then take the next element of each label which is the input.
Live test case.
If you don't mind an extra file, with PHP.
You'd need to make a small php file to echo all the form information like this:
<?php
$label1 = "label1";
$label2 = "label2"; //Set all labels here
$label3 = "label3";
$label4 = "label4";
echo $label1 . " " . $_POST['field1'] . "<br />"; //Change to get depending on your method.
echo $label2 . " " . $_POST['field2'] . "<br />";
echo $label3 . " " . $_POST['field3'] . "<br />";
echo $label4 . " " . $_POST['field4'] . "<br />";
echo "Done.";
?>
and put that in it's own file. Set the form's action attribute to that file and it will print out all the data.
One method, without a JavaSCript library, is:
var form = document.getElementsByTagName('form')[0];
form.onsubmit = function(){
var labels = document.getElementsByTagName('label');
if (!document.getElementById('container')){
var container = document.createElement('ol');
container.id = 'container';
}
else {
var container = document.getElementById('container');
while (container.firstChild){
container.removeChild(container.firstChild);
}
}
for (var i=0,len=labels.length; i<len; i++){
if(document.getElementById(labels[i].getAttribute('for'))){
var newLi = document.createElement('li');
var iText = document.createElement('span');
newLi.innerHTML = labels[i].innerHTML;
iText.innerHTML = document.getElementById(labels[i].getAttribute('for')).value;
newLi.appendChild(iText);
container.appendChild(newLi);
}
}
document.getElementsByTagName('body')[0].appendChild(container);
return false;
};
JS Fiddle demo.
References:
node.appendChild()
document.createElement().
document.getElementById().
document.getElementsByTagName().
element.getAttribute().
element.innerHTML.
for () {...}.
node.firstChild.
node.removeChild().
while () {...}.
You may get the value for labels and fields in javascript using
var label1 = getElementById("id").name
Create a string formatted as you want to show the user and show all the values with
document.write(string);