I have this php code which populates a select with a list of .js files from a directory.
<select id="s1" name="s1">
<option value="" selected="selected">Select Employee</option>
<?php
foreach(glob(dirname(__FILE__) . '/*.js') as $filename){
$filename = basename($filename, ".js");
echo "<option value='" . $filename . "'>".$filename."</option>";
}
?>
</select>
I have this script tag later on that loads a .js file:
<script src="data.js"></script>
How would I change the src attribute depending on the user selection of a file and refresh the page to demonstrate the contents with the new .js file?
It won't work by just altering the src attribute of an existing script because the browser will only parse that element one time. Changing the src after it's been parsed won't cause it to reload.
Instead, you need to create an entirely new script element, which you would then conditionally configure the src of and then append that into the document.
// Get a reference to the select
var select = document.getElementById("s1");
// Set up a change event handler for it:
select.addEventListener("change", function(){
// Create a new `<script>` element
var script = document.createElement("script");
// Conditionally set the src for the element
switch(this.value){
case "John" :
script.src = "john.js";
break;
case "Mary" :
script.src = "mary.js";
break;
case "Dave" :
script.src = "dave.js";
break;
}
// Append the element to the document
document.querySelector("head").appendChild(script);
// Just for testing... scroll to the bottom to see the
// newly created element
console.log(document.querySelector("head").innerHTML);
});
<select id="s1" name="s1">
<option value="" selected>Select Employee</option>
<option>John</option>
<option>Mary</option>
<option>Dave</option>
</select>
But, consider that if the user were to change the selected item from the dropdown, another new script element would be created and, in the end, you could wind up with a new script for each of the items. In which case, you may want to just consider statically linking to just one script file and having different functions within it and then just calling the right function based on the value of the dropdown list.
Related
When I try to load the first .load it passes 1 variable without any problem, I receive this variable from a _GET method to store it in a data-id button attribute to pass it back to another .load, in this second file I receive the variable again in a _GET method and the code does its thing, but when doing the process again from the beginning, in the second .load the variable is duplicated and the alert() script shows 2 times, as well as the process of this same file too.
I have tried with .empty() and .remove() functions, likewise I have tried to load from the last .load the first file that filters the main file, but the problem still occurs.
(The main to send variable to first file in .load)
<p>Select a category</p>
<select name="category" id="category" class="form-control" required>
<option disabled selected value>category</option>
<option value="1">all cat</option>
</select>
<div id="table-category" name="table-category"></div>
$("#consult").click(function(e){
e.preventDefault();
idCategory = $('#category').val();
$('#table-category').load('../public/tabla-proyectos.php?v1='+idCategory );
});
The second .load in that id="table-category"
$category = $_GET['v1'];
<script>
alert(<?php echo $category;?>); <!-- In this part dont have problems with the variable because return only one result -->
</script>
<button id="admin" name="admin" data-id="<?php echo $category;?>">Show</button>
<div id="map"></div>
<script>
$(document).on("click", "#admin", function () { <!-- I think there's the problem -->
category = $(this).data('id');
$('#map').load('../public/mapa.php?val1='+category);
});
</script>
Final .load file
$categoy_id = $_GET['val1'];
<script>
alert(<?php echo $category_id;?>); <!-- The first time OK, but trying again from the beginning repeat the process 2 times -->
</script>
I have solved it in the following way:
I have taken the script of the second file and I have put it in the main file, adding to it an .empty() function so that it cleans all its values before returning to show a new result inside this div, I have also added a new script inside the last .load file being the following:
Main file now see like:
$("#consult").click(function(e){
e.preventDefault();
idCategory = $('#category').val();
$('#table-category').load('../public/tabla-proyectos.php?v1='+idCategory );
});
$(document).on("click", "#admin", function () {
$('#map').empty();
category = $(this).data('id');
$('#map').load('../public/mapa.php?val1='+category);
});
The second file .load don't have script because now is on the main
The last file script now see like:
idCategory = $('#category').val();
$('#table-category').empty();
$('#table-category').load('../public/tabla-proyectos.php?
v1='+idCategory );
I'm trying to pass a value of a option in a select from my HTML form to a PHP variable through Javascript
<script type="text/javascript">
function changeDir(ID){
var dir = document.getElementById(ID).value;
//For debuging purposes i've used an alert to show the value of dir on screen
//alert (dir);
//At this point of the function I want to assign the value of "dir" to the variable $folder
}
</script>
there's my .php with html
<SELECT name="course" ID="course" onchange='changeDir("course")' >
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
<?php $folder= ...?>
I'm using this with a php upload lib, all working at the same file.
If anyone can explain me how to assign the value of the option to a php var will be great.
Thanks and Regards.
You can choose 2 different ways. First is AJAX, second is to redirect the page and GET the value of the <select> element.
HTML:
<SELECT name="course" ID="course" onchange='changeDir("course")' >
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
JAVA:
<script type="text/javascript">
function changeDir(ID){
var dir = $("course").val();
$.post("php_file.php",
{
posted_dir: dir
},
function(data){
$("id_of_result_elemnt").html(data);
});
}
</script
PHP:
<?php
$folder=$_POST['posted_dir'];
echo "This text will be display in the element with id_of_result_elemnt ID";
?>
Other method is redirect
HTML+PHP:
<SELECT name="course" ID="course" onchange='changeDir("course")' >
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
<?php if (iset($_GET['folder']))
{$_GET['folder']=$folder;}...?>
JAVA:
<script type="text/javascript">
function changeDir(ID){
var dir = document.getElementById(ID).value;
window.location = "http://example.com/myphp?folder=" + dir;
}
</script>
The fact is that you can't. They both live in different parts of your page. While you can write them in the same file, all PHP code is processed in the server side and Javascript is not able to see anything from the client side.
What you could do is whether pass it as a AJAX request in order to get back some information to show to the user or make the <select> refresh the page when user changes the option by submitting the form, so you don't lose the "state" of your form, and then verify in your php block if there's any option selected.
I have 2 html files(a.html and index.html) and 1 javascript file(file.js) In a.html-------i have a drop-down menu of different languages(like english,german,hindi). From the drop down 1 of the language is selected.
<select ng-model="lang" class="form-control input-custom input-sm" ng-change="language(lang)" required>
<option value="" selected>--Choose language--</option>
<option value="en-us">english</option>
<option value="id-id">indonesia</option>
</select>
file.js---Based on the language selected from a.html file, i update the index.html file.
$scope.language=function(lang){
var search_quarry = "bower_components/angular-i18n/angular-locale_" + lang + ".js";
var scr = document.createElement("script");
scr.src = search_quarry;
document.getElementsByTagName("body")[0].appendChild(scr);
console.log(document);
}
In file.js if i do console.log(document)...it shows that the script tag is attached in the body of index.html. But the result is not reflected when i select the language.
script tag for appending to index.html
<script src="bower_components/angular-i18n/angular-locale_id-id.js"></script>
index.html-----
If i append the script tag manually in index.html the result is shown but when i dynamically updates it..the script tag gets attached to index.html file but the results are not reflected. How can i reload index.html such that the dynamically added content also reflects while running the application?
Try using setAttribute() instead of direct assignment, change:
scr.src = search_quarry;
to
scr.setAttribute('src', search_quarry);
I am trying to pass 2 values via URL to another page. I know how to do this however I am taking one of the values from the result of select box. I am grabbing the selected value and storing it in a variable then attempting to post this variable in the URL.
option 1 is storing the selected value.
<select name = 'ADDITIONALINFO' id = 'ADDITIONALINFO'>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
<script>
var sel = document.getElementById("ADDITIONALINFO");
sel.onchange = function()
{
var option1 = sel.options[sel.selectedIndex].text;
alert(option1);
};
</script>
<?php
echo "<div class=\"add-button-quote\">Get a Quotation</div>";
The problem Im having is when I click the button the URL it takes me too displays the $sku but not $option1.
If anyone can spot where Ive gone wrong I would really appreciate your advice. Thanks!
PHP is not run while the page is active, it's only run until the page is loaded. From there you have to rely on javascript.
If $product->PR_SKU and $o->OP_NAME is set by PHP you don't have to change that part, but remove OP_NAME from the url. After getting the option selected you can then add the parameter by javascript.
Notice that you might want to store the baseUrl somewhere else instead of writing like below, where you will potentially get duplicates of the parameter:
document.getElementById("your-link").href += "&OP_NAME=" + option1;
Do like this instead:
var baseUrl = <?php echo "/quotation/index.php?sku=" . $product->PR_SKU . "&OP_NAME2=" . $o->OP_NAME; ?>
var sel = document.getElementById("ADDITIONALINFO");
sel.onchange = function()
{
var option1 = sel.options[sel.selectedIndex].text;
document.getElementById("your-link").href = baseUrl + "&OP_NAME=" + option1;
};
Your div can look like this (notice the removal of option1 and the id='your-link':
<?php
echo "<div class=\"add-button-quote\"><a id=\"your-link\" href=\"/quotation/index.php?sku=" . $product->PR_SKU . "&OP_NAME2=" . $o->OP_NAME . "\">Get a Quotation</a></div>";
?>
Give the div an id and change javascript function to:
sel.onchange = function()
{
var option1 = sel.options[sel.selectedIndex].text;
document.getElementById("add-button-quote").innerHTML = "<a href='/quotation/index.php?sku=<?php echo $product->PR_SKU;?>&OP_NAME="+encodeURIComponent(option1)+"&OP_NAME2=<?php echo $o->OP_NAME;?>'>Get a Quotation</a>";
alert(option1);
};
Or give anchor an id and the same way manipulate its href attribute.
Here is an example of form with POST method with javascript onchange event -etched- directly to select tag. This should work *(haven't tested though) and if it does, it won't take a lot of Your time to adapt this to GET instead of POST.
<form id="UNIQUEID" method="POST" action="#">
<select id="ADDITIONALINFO" name="ADDITIONALINFO" onchange="document.forms['UNIQUEID'].submit();">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
</form>
One more thing...
USE singlequotes when mixing php and html - wherever possible and don't forget to write php close tag.. ?> - ALSO .. this -> & should be & inside href tag when url query is not -text/plain- (javascript) but -text/html-.
Example with php shortEcho:
<?= instead of <?php echo (I assume that Your server is configured to use php shorthands):
<?='<div class="add-button-quote"> Get a Quotation </div>'; ?>
HOwever, as people already stated here, $option1 variable is not going to work on the way You want.
With additional $option1=$_GET['ADDITIONALINFO']; or $option1=$_POST['ADDITIONALINFO']; (whichever You decide to use, depending on form method) somewhere in between, and before <div class="add-button-quote"> .. might work. :)
$option1 is not defined in PHP (it's a variable in JavaScript, right?) You can not mix up JS and php in that way ;)
Use onclick instead of onchange, it should do the trick...Like #Florian asks, why not using a form?
Also, you should define option1 outside onclick/onchange scope, and use it as a javascript variable, without '$', once it is not a PHP variable
I have some html code used in more than one place, I put it in a .php file and include it where needed. In one case I include this code inside a form.
This form has one element; and just below that, inside the form, is the include for the php file that has the html code.
I find that the included html from the .php file cannot access the form element but the one element that is on the same page as the form has no such trouble.
Here's the included code that's in a separate .PHP file:
// inside theIncluded.php
<div id="aDivToBeIncluded">Testing</div>
And here is my form declaration -- the signature looks overly complex because I removed other elements (text boxes, etc) for this explanation:
<form style="display: inline-block" name="areaComboboxForm" method="post"
autocomplete="off" enctype="multipart/form-data">
<select name="mySelect" id="mySelectId" onchange="return doChange(this)" >
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
<?php require_once("theIncluded.php") ?>
</form>
And here is the troublesome code:
function doChange(theSelect)
{
var theSelect = document.getElementById('mySelectId');
// THIS REPORTS THAT THE FORM IS 'objectHTMLFormElement'
alert("doChange(), the form is: " + theSelect.form);
var theIncludedDiv= document.getElementById('aDivToBeIncluded');
// THIS REPORTS THAT theIncludedDiv IS 'objectHTMLDivElement'
alert("doChange(), the included Div is: " + theIncludedDiv);
// THIS REPORTS THAT theIncludedDiv.form IS 'undefined'
alert("doChange(), the form is: " + theIncludedDiv.form);
}
To recap, I include some html code from a .php file that has one DOM element, a div.
That div, when accessed on the page where its .php file is included, resolves to an
objectHTMLDivElement.
But when I try to access the .form that the objectHTMLDivElement is included on -- the form is 'undefined.'
Is there a reason for this? All this code is in the same folder on the same webserver, a localhost XAMPP web server.
According to your code, the div is inside the form and has no .form of its own.
You'd be looking for theIncludedDiv.parentNode if you wanted the form element.
.form is only a property of HTMLInputElements in HTML4 and in HTML5 it has some different behavior(it can be the id of the form element or null).