How to pass a javascript variable in a PHP url?? - javascript

I would like to redirect to the chosen page after having validated the form.
I started this:
<form action = "planning.php?court= variable" method = "POST">.
<script>
function courtNumber () {
var variable = document.getElementById ("tennis_court"). value;
alert (variable);
}
</script>
I catch the correct value in my alert when I click on validate, now I would like to insert it in my tag.
Thank you.

You can reassign the action of the form.
function courtNumber () {
var variable = document.getElementById("tennis_court").value;
document.querySelector("form").action = "planning.php?court=" + encodeURIComponent(variable);
}

First you can add one id to your form, so you can access it in your function.
<form action = "planning.php?court= variable" method = "POST" id="myForm">
</form>
Then, in your script you can acces the action property and set the value there.
<script>
function courtNumber ()
{
var variable = document.getElementById("tennis_court").value;
alert (variable);
document.getElementById("myForm").action = "planning.php?court=" + variable;
}
</script>

Related

Access return value from event Listener callback function from main program?

I have a form which contains an input field and a submit button. The whole program depends on the submission of the form to continue. Each function can only perform one task as follows:
Get input value
Output the value
allEvents();
//output(name)
function allEvents(){
document.getElementById('formOne').addEventListener('submit',getInputValue)
}
function getInputValue(e){
e.preventDefault()
let name = document.getElementById('inputText').value;
return name;
}
function output(n){
console.log(n)
}
<form id="formOne">
<input type="text" id="name" required>
<input type="submit" id = "inputText">
</form>
How do I access the value of name after the form has submitted in the main program, so that I can pass it to function output().
Note: Function inputText() can only return the input name.
You stated that you want each function to do different things. This is a good idea, but then take a look at this function:
function getInputValue(e){
e.preventDefault()
let name = document.getElementById('inputText').value;
return name;
}
Is this getting the input value only? Nope, it is preventing the default behavior of e as well. But you will want to get the input value later as well. This is not only getting the value, but setting it as well. Now, first things first, let's define a prototype for this purpose.
function InputOutput() {
var inputs = {}; //This will contain key-value pairs.
this.setInputValue = function(name, val) {
inputs[name] = val;
};
this.getInputValue(name) {
return inputs[name];
}
this.getNames() {
var result = [];
for (var key in inputs) result.push(key);
return result;
}
}
Now, lets instantiate this and use it:
//output(name)
function allEvents(){
document.getElementById('formOne').addEventListener('submit',function(e) {
e.preventDefault(); //Are you sure you do not want to execute the submit?
let tag = document.getElementById('inputText');
let name = tag.name;
let value = tag.value;
inputOutput.setInputValue(name, value);
});
}
var inputOutput = new InputOutput();
allEvents();
and later you can get the names by using getNames, like this:
function output(name) {
consolge.log(inputOutput.getInputValue(name));
}
and calling it like this:
output(inputOutput.getNames()[0]);
EDIT
Of course you can avoid the usage of global variables, by wrapping a lot of things into a function which will be the value of onload of your body tag, but that's a different question.
Because getInputValue() returns the name, you can pass it directly to output(name) .
allEvents();
function allEvents(){
document.getElementById('formOne').addEventListener('submit',output(getInputValue))
}
function getInputValue(e){
e.preventDefault()
let name = document.getElementById('inputText').value;
return name;
}
function output(n){
console.log(n)
}
You would have to declare the variable name outside of the function scope.
let name
function allEvents(){
document.getElementById('formOne').addEventListener('submit',getInputValue)
}
function getInputValue(e){
e.preventDefault()
name = document.getElementById('inputText').value;
return name;
}
function output(n){
console.log(n)
}
output(name)
However, why not just call your output function from within your getInputValue value?
function allEvents(){
document.getElementById('formOne').addEventListener('submit',getInputValue)
}
function output(n){
console.log(n)
}
function getInputValue(e){
e.preventDefault()
let name = document.getElementById('inputText').value;
output(name)
return name;
}
Jiminy Cricket. Reading through all of this "stuff", I couldn't decide which was more messed-up. The question, or the answers !
Looking at the Question:
function allEvents(){
document.getElementById('formOne').addEventListener('submit',getInputValue)
}
Why would anyone be adding an Event Listener to formOne ? What does the form have to do with anything ? It's useless.
And continuing with the Question,
function getInputValue(e){
e.preventDefault()
let name = document.getElementById('inputText').value;
return name;
}
Why would anyone be getting an Element by ID of inputText ? Seriously. What does that have to do with anything ? That is essentially the "Submit" button. You aren't going to find anyone's name in the interior of a button.
And then there was the Note that he added underneath his question ... Sorry, but there is no Function called inputText().
And now for the first Answer ( the one that has 2 up-votes ); Is that supposed to be JavaScript ? I typed it in, and it doesn't run. It basically has an error on every line.
And for the second answer ( with one up-vote ), I typed that one in too. It doesn't run either.
I hope the original poster is willing to make a modification to his HTML. Because I tried running his code in Internet Explorer and Chrome, and they don't treat his HTML structure the same, because his "Submit" button does not include the value attribute. So each Browser has to take a guess about what value to insert.
So if he will scrap his "pseudo-Submit" button, and replace it with a real Submit button :
<button type="submit" id="inputText">Submit</button>
And also, allow me to add an HTML paragraph tag to print the results in, because I think console.log ought to be banned.
<p id="outputIDname" ></p>
Then here is some code that actually runs. ( And I have also included the console.log statements for the people who need it. )
allEvents( ) ;
// output(name)
function allEvents( ) {
document.querySelector( "#inputText" ).addEventListener( "click", output ) ;
}
function output( e ) {
e.preventDefault() ;
let tempName = getInputValue( ) ;
console.log( "name Inside of Output Function = " + tempName ) ;
document.querySelector( "#outputIDname" ).innerHTML = tempName ;
}
function getInputValue( ) {
let name = document.getElementById( 'name' ).value ;
console.log( "name Inside of Input Function = " + name ) ;
return name ;
}
Here is the modified HTML :
<form id="formOne">
<input type="text" id="name" required>
<button type="submit" id="inputText">Submit</button>
</form>
<p id="outputIDname" ></p>
Here is the output:
// name Inside of Input Function = John
// name Inside of Output Function = John
// And the here is the output that is printed inside of the
// Paragraph Tag that I added to his HTML structure:
// John
And if you want to see just how much the Browsers hated his "Submit" button, just try replacing my "Submit" button with the one that he had. The Java Script will no longer work.
And one final note: Internet Explorer is so dumb, that ( if you replace my "Submit" button with the one that he had ), Internet Explorer doesn't even realize that the Java Script is not working. If you look in console.log, you will see that Internet Explorer just happily prints out 'John' and 'John', as if there is nothing wrong. But the Paragraph Tag ( that I added to the page ) remains empty. Just one of many reasons to ban console.log

How to pass a String variable to javascript onClick Function in a JSP

In my jsp, I have something like this
<%
String isMultipleOfficesExists = (String)request.getAttribute("MultipleOfficesExists");
String isMultipleOfficeSecurity = (String)request.getAttribute("MultipleOfficeSecurityExists");
String envParm = "default";
if("true".equals(isMultipleOfficesExists)){
envParm = "multipleOffice";
}else if("true".equals(isMultipleOfficeSecurity)){
envParm = "multipleOfficeSecurity";
}
%>
At the bottom of my form, in my submit button, I am calling a JavaScript On-click function.
<input class="white_button_extra_large" type="button" value="<%=goBtn%>" onclick="javascript:selectEnvironment(envParm);">
And my script section is :
function selectEnvironment(envParm)
{
resetToken();
logoutFlag = false;
document.forms[0].action = contextURL+'/login/selectEnvironment?envParam=' +envParm;
document.forms[0].submit();
}
But I am getting Uncaught ReferenceError: envParam is not defined
How can I solve this?
Make your envParm variable global in JSP. And your on click event should be like follows
<input class="white_button_extra_large" type="button" value="<%=goBtn%>" onclick="javascript:selectEnvironment('<%=envParm%>')">
You should pass the value from javascript function. The parameter should have value. Refer this linkPassing arguments

from submit and print result at the same time update with url extenstion

var solve = function () {
var str = document.getElementById('equ').value;
document.getElementById('demo').innerHTML=str;
}
<form onsubmit="return solve()">
<input type="equation" id="equ" name="equation">
<button>solve</button>
</form>
<p id="demo"></p>
I have form submit code.On the time of submit the input data print to #demo .but the page will be reloated. so the #demo data was empty. if i applied return false statement data will print.but not update with my url
.
My question is print the data to html page and also update the url
with given input data like 'index.html?equation=mydata'.
please give ah code for satisfy the both condition.
here is my fiddle
<form onsubmit="return solve()">
<input type="equation" id="equ" name="equation">
<button>solve</button> </form>
<p id="demo"></p>
Js
var solve = function () {
var str = document.getElementById('equ').value;
document.getElementById('demo').innerHTML=str;
console.log(str);
}
For your condition , I seem using javascript session localStorage is suitable
set your js session by setItem(key,value)
get your js session by getItem(key)
document.getElementById('demo').innerHTML= localStorage.getItem("demo");
var solve = function () {
var str = document.getElementById('equ').value;
localStorage.setItem('demo',str);
}
I got it working (in the fiddle) by setting the first HTML record as:
<form onsubmit="solve()">
i.e., the return was removed.
You still get another error I guess from the `document.getElementById('demo').innerHTML=str;', but this can be further investigated.

updating a json value with angular

I am trying to update an json object value from a textbox using angular and I'm not sure what the best way to go about it is.
This is the json object...
$scope.productAttributes = {
"CostRequirements":[
{
"OriginPostcode": 'NW1BT',
"BearerSize":100
}
]
}
And when a use types in a text field and clicks a button, I would like to grab that textfield value and pass it into the json object to replace the postcose value (OriginPostcode) I tried to pass in a scope variable but that didnt work.
<input type="text" placeholder="Please enter postcode" class="form-control" ng-model="sitePostcode"/>
And this is the fucntion that is fired when the user clicks a button to submit the json
var loadPrices = function () {
productsServices.getPrices1($scope.productAttributes)
.then(function (res) {
$scope.selectedProductPrices = res.data.Products;
// $scope.selectedProductAddOns = res.data.product_addons;
})
.finally(function () {
$scope.loadingPrices = false;
$scope.loadedPrices = true;
});
};
Could anyone tell me what I need to do to put the user input in the textbox into the json object?
Many thanks
What we don't see is the function that runs the update with the button. It should look something like this
// your HTML button
<button ng-click='updateThingy()'>Update</button>
// your HTML input
<input type="text" ng-model="myObject.sitePostcode"/>
// your controller
$scope.myObject = { // ties to the ng-model, you want to tie to a property of an object rather than just a scope property
sitePostcode : $scope.productAttributes.CostRequirements[0].OriginPostcode // load in post code from productAttributes
};
$scope.updateThingy = function(){
$scope.productAttributes.CostRequirements[0].OriginPostcode = $scope.myObject.sitePostcode;
};
Here is a demo plunker for updating a value on button click, hope it helps out.
http://plnkr.co/edit/8PsVgWbr2hMvgx8xEMR1?p=preview
I guess loadPrices function is inside your controller. Well, then you should have sitePostCode variable available inside your controller and your function. So you just need to inject that value inside $scope.productAttributes.
$scope.productAttributes.sitePostCode = $scope.sitePostCode;
This you need to put it before you make the productsServices.getPrices1 call.
var loadPrices = function() {
$scope.productAttributes.sitePostCode = $scope.sitePostCode;
productsServices.getPrices1($scope.productAttributes)
.then(function(res) {
$scope.selectedProductPrices = res.data.Products;
// $scope.selectedProductAddOns = res.data.product_addons;
})
.finally(function() {
$scope.loadingPrices = false;
$scope.loadedPrices = true;
});
};
Let me know if it worked.

How to return a variable from a javascript function into html body

I am still new to javascript, and I am trying to get a function to return a variable using html & javascript. Basically the function should just return whichever radio button that the user clicks on, although at the moment I don't see anything being returned at all.
The function is here:
<script type="text/javascript">
function GetSelectedItem() {
var chosen = ""
len = document.f1.r1.length
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
chosen = document.f1.r1[i].value
}
}
}
return chosen
</script>
And then in the html section I have these radio buttons, and my attempt to get the variable "chosen" output to the screen.
<form name = f1><Input type = radio Name = r1 Value = "ON" onClick=GetSelectedItem()>On
<Input type = radio Name = r1 Value = "OFF" onClick =GetSelectedItem()>Off</form>
<script type ="text/javascript">document.write(chosen)</script>
At the moment nothing seems to be getting returned from the function (although if I output the variable 'chosen' inside the function then it is working correctly.
Thanks in advance!
Here's a little simpler approach.
First, make a few corrections to your HTML, and create a container to display the output:
<form name = "f1"> <!-- the "this" in GetSelectedItem(this) is the input -->
<input type = "radio" Name = "r1" Value = "ON" onClick="GetSelectedItem(this)">On
<input type = "radio" Name = "r1" Value = "OFF" onClick ="GetSelectedItem(this)">Off
</form>
<div id="output"></div>
Then change your script to this:
<script type="text/javascript">
// Grab the output eleent
var output = document.getElementById('output');
// "el" is the parameter that references the "this" argument that was passed
function GetSelectedItem(el) {
output.innerHTML = el.value; // set its content to the value of the "el"
}
</script>
...and place it just inside the closing </body> tag.
Click here to test a working example. (jsFiddle)
document.write takes a string, and outputs it as part of the HTML. This is not a live value that updates when the variable pointing at the string is updated.
For that, you will need to perform DOM manipulation.
Change your JavaScript function to something like that:
<script type="text/javascript">
function GetSelectedItem() {
len = document.f1.r1.length;
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
document.getElementById('test').textContent = document.f1.r1[i].value;
}
}
}
</script>
And then in the body:
<div id="test"></div>
As I put in the post. Using JQuery would make your life easy for this kind of task (and many others for the matter). The really nice thing about JQuery is that it often makes your JavaScript syntax much easier then you can learn the nitty gritty details of javascript as you go.
First, add the following script tag into your html page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
Now you have the JQuery API
Then you could rewrite the function like this.
function GetSelectedItem(btnRadio)
{
var jqElem = $(btnRadio);
$('#output').html(jqElem.attr('value')); //attr('<name of attributre'>) gets the value of the selected attribute
}
Your html would look like this
<form name = "f1">
<input type = "radio" name = "r1" value = "On" onclick="GetSelectedItem(this)">On
<input type = "radio" name = "r1" value = "Off" onclick ="GetSelectedItem(this)">Off
</form>
<div id="output">
</div>
More or less, the .html() can both get and set the html of the selected element. So we are just simply inserting the value into the div tag.

Categories

Resources