How to get the html Select value in php?
i have made this Select in html
<select id="year" onchange="filterYear();">
</select>
Function to fill in the Select:
var n = 22;
function selectOne() {
var select = document.getElementById('year');
for (var i=5; i<n; i++) {
select.options[select.options.length] = new Option(i+1, i);
}
}
but i need to read the current selected item from the select.
i tried this (javascript):
function filterYear() {
var e = document.getElementById('year');
var value = e.value;
var text = e.options[e.selectedIndex].text;
alert(text);
}
php:
$text = $_GET['text'];
echo $text;
but this did not work
any ideas on how to fix this
i hope someone can push me in the right direction
Without submitting a form and thus reloading the page you can easily send an ajax request that can be processed by the PHP server script. The response from the server is then used in the callback to, usually, perform further DOM manipulation or whatever.
var n = 22;
function selectOne() {
var select = document.getElementById('year');
for( var i = 5; i < n; i++ ) {
select.appendChild( new Option( i + 1, i ) );
}
}
// build the menu
selectOne();
// bind event listener externally
document.getElementById('year').addEventListener('change',e=>{
// a callback to process response from PHP script
let callback=(r)=>{
alert(r)
};
// send a GET ajax request and process response
fetch( 'path/to/php/script.php?text='+e.target.value )
.then(r=>r.text())
.then(callback)
.catch(alert)
})
<select id="year" name='year'>
</select>
Related
I want to know how to remove an input value before submitting a profile form in Wordpress with Ultimate Member plugin. I've been stuck with this for a whole week.
The thing is that I have conditional fields in the profile form that if the user does not select, they still save their values when the form is submitted. The plugin does not remove the values from the hidden fields conditionally, which is a problem if you want to send these fields elsewhere with REST API.
I couldn't do it with PHP so I added a script inside the principal function to try and clear the values. This work when user refresh the form, but not when user submit the form with the hook um_after_user_updated
function remove_before_send () {
?>
<script>
var elements = document.querySelectorAll('.um-is-conditional');
for (var i = 0; i < elements.length; i++) {
elements[i].childNodes[1].childNodes[0].value = "";
}
</script>
<?php
}
add_action('um_profile_content_main', 'remove_before_send');
EDIT:
Thanks to the comment of #JB_DELR. You really gave me all the clues.
This is my final code (im not proud, because i wanted to use php, but this is the best i could do)
function remove_before_send () {
?>
<script>
var boton = document.querySelector("div.um-left.um-half > input");
boton.addEventListener("click", function(){
var elements = document.querySelectorAll('.um-is-conditional');
for (var i = 0; i < elements.length; i++) {
if (elements[i].style.display == "none") {
elements[i].childNodes[1].childNodes[0].value = "";
}
}
});
</script>
<?php
}
add_filter( 'um_profile_content_main', 'remove_before_send');
Your js script need to handle the form submit event, prevent default submiting, remove unnecessary fields an submit the form itself.
Something like this:
<script>
var form = document.querySelector(<select the form>);
form.onsubmit = function(e) {
e.preventDefault(); // don't submit the form right now;
var elements = document.querySelectorAll('.um-is-conditional');
for (var i = 0; i < elements.length; i++) {
elements[i].childNodes[1].childNodes[0].value = "";
}
// to remove element, this remove the input field, so field is no more in the request
// elements[i].childNodes[1].removeChild(elements[i].childNodes[1].childNodes[0]);
}
form.submit();
</script>
I have a dropdown that is filled by a database and everything works well. However I want to pass a parameter to php based on the value of the dropdown which I can do. If I force the var to have a particular number it gets the corresponding item in the database. I'm having a problem to get the value of a dropdown. I've tried all the suggestions here in the forum and nothing works in this particular area of my code. I have it working on another piece of my code but not on this particular one and I don't know why. Here is my code:
<select id="servicos" onChange="return selectServ();">
<option value="item" class="itemoption">Serviço</option>
This is the code that is not working:
function selectServ() {
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
$.getJSON("http://ib.esy.es/gestao/_php/servicos_threadingpreco.php", { serv: idserv }, null).then(function(data) {
console.log(data);
var tr = data
for (var i = 0; i < data.length; i++) {
var tr = $('<tr/>');
// Indexing into data.report for each td element
$(tr).append("<td>" + data[i].preco + "</td>");
$('.table1').append(tr);
}
});
}
If I put
var idserv = "1"
It is working, however this:
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
Is not getting a value. The console log gives:
selectdynamicpreco.html:76 Uncaught TypeError: $(...).value is not a function
You should consider using jQuery to get the value of the dropdown:
$('#dropdown').val() will give you the selected value of the drop down element. Use this to get the selected options text.
$("#dropdown option:selected").text();
Should get you the text value of the dropdown.
This is working on another piece of the code
<script>
function selectCat(){
$('#servicos').change(function() {
$('#demo').text($(this).find(":selected").text());
});
//for textbox use $('#txtEntry2').val($(this).find(":selected").text());
var e = document.getElementById("categoria");
var servSelected = e.options[e.selectedIndex].value;
var url = "";
var items="";
if(servSelected === "1"){
url = "http://ib.esy.es/gestao/_php/servicos_threading.php";
}
if(servSelected === "2"){
url = "http://ib.esy.es/gestao/_php/servicos_sobrancelhas.php";
}
if(servSelected === "3"){
url = "http://ib.esy.es/gestao/_php/servicos_manicure.php";
}
$.getJSON(url,function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.ID+"'>"+item.servico+"</option>";
});
$("#servicos").html(items);
});
};
</script>
I already have this code working for 2 selection menus, now I am trying to add a third but the third is just showing all of the sub-sub categories, rather than being based on the previous selections..
Here is the menu code, I'll just show 1 selection example so it's easier to read.
<select name="category" id="category">
<option value="Sport">Sport</option>
</select>
<select name="sub_category" id="sub_category">
<option value="Golf" class="Sport">Golf</option>
</select>
<select name="subsub_category" id="subsub_category">
<option value="Mens" class="Golf">Mens</option>
<option value="Ladies" class="Golf">Ladies</option>
</select>
JS CODE
<script src="js/menu.js"></script>
<script type="text/javascript">
window.onload = function() {
dynamicSelect("category", "sub_category", "subsub_category");
}
</script>
MENU.JS
function dynamicSelect(id1, id2, id3) {
// Browser and feature tests to see if there is enough W3C DOM support
var agt = navigator.userAgent.toLowerCase();
var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_mac = (agt.indexOf("mac") != -1);
if (!(is_ie && is_mac) && document.getElementById && document.getElementsByTagName) {
// Obtain references to both select boxes
var sel1 = document.getElementById(id1);
var sel2 = document.getElementById(id2);
var sel3 = document.getElementById(id3);
// Clone the dynamic select box
var clone = sel3.cloneNode(true);
// Obtain references to all cloned options
var clonedOptions = clone.getElementsByTagName("option");
// Onload init: call a generic function to display the related options in the dynamic select box
refreshDynamicSelectOptions(sel1, sel2, sel3, clonedOptions);
// Onchange of the main select box: call a generic function to display the related options in the dynamic select box
sel1.onchange = function() {
refreshDynamicSelectOptions(sel1, sel2, sel3, clonedOptions);
};
}
}
function refreshDynamicSelectOptions(sel1, sel2, sel3 clonedOptions) {
// Delete all options of the dynamic select box
while (sel2.options.length) {
sel2.remove(0);
}
// Create regular expression objects for "select" and the value of the selected option of the main select box as class names
var pattern1 = /( |^)(select)( |$)/;
var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
var pattern3 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
// Iterate through all cloned options
for (var i = 0; i < clonedOptions.length; i++) {
// If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box
if (clonedOptions[i].className.match(pattern1) || clonedOptions[i].className.match(pattern2) || clonedOptions[i].className.match(pattern3)) {
// Clone the option from the hidden option pool and append it to the dynamic select box
sel2.appendChild(clonedOptions[i].cloneNode(true));
sel3.appendChild(clonedOptions[i].cloneNode(true));
}
}
}
Edit: Had to change a lot to get it working, but it is working now, here: http://jsfiddle.net/kvAWf/11/
Here's the resulting Javascript:
var sel1 = document.getElementById('category');
var sel2 = document.getElementById('sub_category');
var sel3 = document.getElementById('subsub_category');
// Clone the dynamic select box
var clone2 = sel2.cloneNode(true);
var clone3 = sel3.cloneNode(true);
// Obtain references to all cloned options
var clonedOptions2 = clone2.getElementsByTagName("option");
var clonedOptions3 = clone3.getElementsByTagName("option");
sel1.onchange = function(){
refreshSelect2();
}
sel2.onchange = function(){
refreshSelect3();
}
function refreshSelect2() {
while (sel2.options.length) {
sel2.remove(0);
}
var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
for (var i = 0; i < clonedOptions2.length; i++) {
// If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box
if (clonedOptions2[i].className.match(pattern2)) {
// Clone the option from the hidden option pool and append it to the dynamic select box
sel2.appendChild(clonedOptions2[i].cloneNode(true));
}
}
refreshSelect3();
}
function refreshSelect3() {
while (sel3.options.length) {
sel3.remove(0);
}
var pattern3 = new RegExp("( |^)(" + sel2.options[sel2.selectedIndex].value + ")( |$)");
for (var i = 0; i < clonedOptions3.length; i++) {
// If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box
if (clonedOptions3[i].className.match(pattern3)) {
// Clone the option from the hidden option pool and append it to the dynamic select box
sel3.appendChild(clonedOptions3[i].cloneNode(true));
}
}
}
I have a JavaScript Object with some information in it.
I have 2 options I can think of to create the HTML from this object. I was wondering which one is the correct way of doing things of is this just all preference?
1) Loop through this array with JavaScript and create the HTML with Jquery?
2) Ajax post/get the object to PHP and loop through this object(php array) and create the HMTL that way? Then return a json encoded object back with the HMTL in it and append it to a div?
What I currently Do to build
var OutterDiv = $(document.createElement('div'));
for loop{
OutterDiv.append("<span>SOME INFO</span>");
var InnerDiv = $(document.createElement('div'));
for loop{
InnerDiv.append("<span>SOME INFO</span>");
InnerDiv.append("<span>SOME INFO</span>");
}
OutterDiv.append(InnerDiv);
}
$("#content").append(OutterDiv);
Why don't you loop through the object and create an HTML string from JavaScript? Then insert that string wherever you need it? I believe this is the fastest way you can accomplish what you want do do. The main idea is that concatenating strings is faster than inserting DOM elements, and perhaps faster than the latency caused by an Http request.
** Edit **
Apparantly, IE is slower at string concatenation (big surprise) and using an array is better.
Example :
var html = [];
for (...) {
html.push( <some html content from your object here> );
}
$(selector).html(html.join(''));
// find the elements you need to handle and perform bindings here
// ex: $('#someelment').click(...);
This is probably as fast as you can get.
** Update **
While performing the task of building HTML with JavaScript is still generally faster, after some testing, it seems that concatenating strings, or building arrays are not faster than creating text nodes. The test can be viewed and forked on jsfiddle.net or here it is for archiving pruposes :
function runTest(testFn, duration) {
var endTime = +new Date() + duration;
var runs = 0;
var charCount = 0;
while (+new Date() < endTime) {
charCount += testFn();
++runs;
}
teardown();
//console.log(testFn.title, 'ran', runs, 'times.');
$('#log').append($('<div></div>').text(testFn.title + ' ran ' + runs + ' times (' + (charCount/1000) + ' cps).'));
}
///
function teardown() {
while (targetDiv.firstChild) {
targetDiv.removeChild(targetDiv.firstChild);
}
}
///
var testData;
var sample, sampleData;
function generateTestData() {
testData = {};
for (var i=0; i < (Math.random() * (sample[1]-sample[0])) + sample[0]; i++) {
testData['item'+i] = randomString();
}
}
function randomString()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789";
for( var i=0; i < (Math.random() * (sampleData[1]-sampleData[0])) + sampleData[0]; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function shuffle(arr) {
var len = arr.length;
var i = len;
while (i--) {
var p = parseInt(Math.random()*len);
var t = arr[i];
arr[i] = arr[p];
arr[p] = t;
}
return arr;
};
///
var $targetDiv = $('#targetDiv');
var targetDiv = document.getElementById('targetDiv');
///
function jq() {
var html = [];
var count = 0;
for (var key in testData) {
count += testData[key].length;
html.push('<div>' + testData[key] + '</div>');
}
$targetDiv.html(html.join(''));
return count;
}
function inner() {
var html = [];
var count = 0;
for (var key in testData) {
count += testData[key].length;
html.push('<div>' + testData[key] + '</div>');
}
targetDiv.innerHTML = html.join('');
return count;
}
function dom() {
var root = document.createElement('div');
var node;
var count = 0;
for (var key in testData) {
count += testData[key].length;
node = document.createElement('div');
node.appendChild(document.createTextNode(testData[key]));
root.appendChild(node);
}
targetDiv.appendChild(root);
return count;
}
///
jq.title = 'jQuery .html';
inner.title = 'innerHTML';
dom.title = 'DOM';
///
sample = [10, 100];
sampleData = [100, 1000];
generateTestData();
var duration = 1000;
var testFn = shuffle([jq, inner, dom]);
$.each(testFn, function(k, fn) {
setTimeout(function() { runTest(fn, duration); }, 0);
});
Overall, while each method is more efficient under some conditions (lots of or few data, long or short strings, etc.), the DOM method seems generally faster in all cases.
So, there you have it. Thanks to GGG for the initial test case.
Do it in javascript. If you already have the data in javascript, taking an extra trip to the server to have PHP do it (letting javascript broker that connection) is wasteful. If it was an intensive calculation, it might make sense to let PHP do it because of speed, but otherwise, seems like a waste.
You could use JSON.stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it.
I am trying to get a sql query to run on drop down menu selection. Here is what I have so far:
<script>
$('#templateid').change(function(DoUpdateOnSelect) {
$.post('page.edit.php?page_id=(-->Need help in getting this id from the page url<--)&template='+this.options[this.selectedIndex].value);
});
</script>
And the drop down:
<select name="templateid" id="templateid" onchange="DoUpdateOnSelect">
<option >Contact</option>
<option >News</option>
<option >Home</option>
</select>
page.edit.php has conditions on it which will run the sql query if it detects the page id and the template in the URL. The template parameter value is grabbed with the jquery (please let me know if that part is set up wrong in the jquery) from the select drop down menu. What I can't figure out is how to grab the page_id parameter from the current url of the page, and insert that into the function so that the page.edit.php?page_id=1&template=Home will be the correctly outputted URL.
Please let me know if you need further information. Thanks in advance.
EDIT: BASED ON ANSWER BELOW:
function querystring(name)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
$('#templateid').change(function() {
var page_id = querystring('page_id');
var url = '?VIEW=EDITPAGE&linklabel='+page_id+'&template='+(this.options[this.selectedIndex].value);
$.post(url);
});
NO CHANGE IS HAPPENING WHEN I MAKE A SELECTION IN THE DROP DOWN MENU
for getting the page_id from the url you should use a function like
function querystring( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
then you could retrieve it with
var page_id = querystring('page_id');
so, your onchange handler would look something like:
$('#templateid').change(function() {
page_id = querystring('page_id');
var url = 'page.edit.php?page_id='+page_id+'&template='+this.options[this.selectedIndex].value);
$.post(url, function(response){
//your logic here
});
});
oh, and please remove the onchange attribute from the select markup:
<select name="templateid" id="templateid">
<option >Contact</option>
<option >News</option>
<option >Home</option>
</select>
Try using this plugin
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});