pass js variable to form action - javascript

I have a dynamic variable in js. I have to get this variable in my form action.
Here is my code
<script type="text/javascript">
$(document).on('click', 'span', function () {
var AutoPath = $(this).attr('automationpath');
// or var AutoPath="Redirect.jsp";
}
</script>
<form action="%{#AutoPath}" method="get">
<input name="AutoRun" id="AutoAction" value="Auto Action" type="submit" />
</s:form>
But this does not redirect to the Redirect.jsp page
If I manually set as below, it will redirect to the Redirect.jsp
<s:set var="formAction" value="'Redirect.jsp'" />
<s:form action="%{#formAction}" >
<input name="AutoRun" id="AutoAction" value="Auto Action" type="submit" />
</s:form>
Can somebody help me with this.

In your javascript code, you are not inserting the automation path into your markup.
Instead the code should look something like this:
$(document).on('click', 'span', function () {
//saving the value to variable
var AutoPath = $(this).attr('automationpath');
//Inserting value int he form
$('form').attr('action', autoPath);
})

I don't know what you are trying to do but if you want to change the action attribute of a form element you simply do the following:
$('form').attr('action','Redirect.jsp');

Related

pass JavaScript variable to HTML input box and (to use in PHP file)

I'm trying to pass a JavaScript variable to the value of an hidden input button to use in my PHP file output.
My HTML is:
<input type = "hidden" id = "location2" name = "location2" value = ""/>
I'm using this onclick="myFunction();" in my "Submit Form" input to run the function as it is not able to be done in the window.load()
My JavaScript below is calling indexes from another function and assigning the text to the variable 'location' (I know this sounds strange but it was the only way I have got it to work so far):
function myFunction() {
var x = document.getElementById("box2").selectedIndex;
var y = document.getElementById("box2").options;
var location=(y[x].text);
document.getElementById("location2").value=(location);
}
Any help would be hugely appreciated as I am really struggling and have been working on this for some time (as you can probably tell, I dont really know what I'm doing) - I just need to call the value of this variable into my PHP file output and the majority of my web form is completed.
Thanks very much
Marcus
I've just changed my HTML as follows
I've removed myFunction from my submit
I've added the following HTML button:
<button onclick="myFunction();" id = "location2" name = "location2" value="">Click me</button>
The variable is now passing!!!! The only problem is when I press the onclick button, it is now submitting my form!!
Is it okay for me to replace my previous submit button with this code??
THANKS TO EVERYONE FOR THEIR HELP ON THIS!!
I Was not sure what you doing but below example may help you. It will post the value as well as the option text.
Here we are using print_r to print the $_POST array from the AJAX Request. using this method, you should be able to debug the issue.
<!DOCTYPE html>
<html>
<body>
<?php if($_POST) {
print_r($_POST); die;
} ?>
<form name="" id="" method="post" >
Select a fruit and click the button:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<input type = "hidden" id = "location2" name = "location2" value = ""/>
<input type = "hidden" id = "locationname" name = "locationname" value = ""/>
<button type="submit" id="submit">Display index</button>
</form>
<script>
function myFunction() {
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect").options;
//alert("Index: " + y[x].index + " is " + y[x].text);
document.getElementById("location2").value=(y[x].index);
document.getElementById("locationname").value=(y[x].text);
//alert($("#location2").val());
}
var submit = document.getElementById('submit');
submit.onsubmit = function(e){
myFunction();
};
</script>
</body>
</html>
i'm assuming your form method is 'POST' and action value is the same php page where you are expecting to see the 'location2' hidden input value, if that is the case, you can use $_POST['location2'] to get the value in that php page.
Yes it is fine to use button tag by default it acts like the submit button inside the form tag. You can also make it act like button(won't submit the form) by using the attribute type='button'.
Edited
button or input type='submit' can submit the form only when it is placed within the form tag(without javascript).
<form action='http://www.stackoverflow.com/'>
<button>stackoverflow</button> <!-- this works -->
</form>
<form action='http://www.stackoverflow.com/'></form>
<button>stackoverflow</button><!-- this won't work -->
var go = function() {
document.forms[0].submit();
};
<form action='http://www.stackoverflow.com/'></form>
<button onclick='go()'>stackoverflow</button><!-- still works -->

Pass js variable to form action url

I'm not sure if this is possible, or if I am doing it the wrong way?
I have a form that when submitted, should send the user to a URL depending on the input.
e.g If the users inputs '2', the URL should be books/itemView?id=2
I have created a var = id, which takes the search input box data. Is it possible to add this variable to my current form action? Perhaps there is a more efficient way?
My current code is as follows;
<form id="search" action="<?php echo URL; ?>books/itemView?id=" method="post">
<input type="text" name="search" id="demo"/>
<input type="submit" value="Submit">
</form>
My JS
$(document).ready(function(){
var id = $('#search').val();
});
Quite new to JS so any help appreciated.
JS should be
$('#search').on('submit', function() {
var id = $('#demo').val();
var formAction = $('#search').attr('action');
$('#search').attr('action', formAction + id);
});
If they enter 2 in the search input then your id will be appended to your url like:
url?search=2
So maybe you want to change the name of your search input to id or add another input field.
<form id="search" action="<?php echo URL; ?>books/itemView" method="post">
<input type="text" name="id" id="demo"/>
<input type="submit" value="Submit">
</form>
That should be all you need no jquery or javascript necessary.
When you submit it should result in:
books/itemView?id=2(or whatever is in the search/id input when you click submit)
Hmm, you can try with that:
$(document).ready(function(){
var $form = $('#search');
var id = $form.val();
var $search = $('#demo');
var originalAction = $search.attr('action');
$form.on('submit', function() {
$search.attr('action', originalAction + id);
});
});
Before submitting the form, jQuery's on('submit', handler) function executes the code in handler modifying the attribute action that you want.
originalAction variable stores the content of the action attribute that was partially generated in php, then you append your id dynamically created with js.

I am testing to capture the submit button value on a form

I am trying to capture the value of a submit button so I can submit the form based on this button being used. The form name incidentform and the button name is updateincidentButton. Below is the code.
$(function(){
$$("#incidentform").submit(function(e){
var =$("#updateincidentButton").val();
if(var==="Update incident"){
alert(var);
e.preventDefault();
}
})
})
Here is the basic html of the form
<form id="incidentform" action="/" method="get">
<input type="submit" class="button" id="updateincidentButton" name="updateincidentButton" value="Update Incident"/>
</form>
var is a reserved keyword in javascript. You can't use it as the name of a variable.
Change this:
var =$("#updateincidentButton").val();
to something like this:
var var1 = $("#updateincidentButton").val();
First off, you don't need two "$$".
Is the name "updateincidentButton" or the id? If it is currently the name, change it to the id:
<button id="incidentform">Click Me</button>
Same thing with the form. The hashtag that is passed into $ represents an id of an element.
First, you have to define your form somewhere...give it an ID:
<form id="aspnetForm">
....
<input type="button" id="updateincidentButton" value="Update incident"/>
</form>
Next, change your JavaScript:
$("#updateincidentButton").click(function(e){
if ($(this).val() == "Update incident"){
$("aspnetForm").submit();
}
e.preventDefault();
return false;
});
Make sure the type of the button is 'button'.
$(document).on('click', '#updateincidentButton', function () {
var value = $('#updateincidentButton').val();
if (value == 'Update incident') {
alert(value);
}
});
Then you won't even have to prevent default. Then submit form using AJAX. Posting to a URL dependent on the value of the button when clicked.

How can I get the value of an input field in javascript without submitting a form?

I'm fairly new to javascript and have a question about how to get a value of an input field without submitting a form. I have the following small piece of code, which I'm using in combination with a realtime-validation script to validate the fields.
<form name="FormName" method="post" />
<input type="text" id="nameValidation" value="HelloWorld" />
<script type="text/javascript">
var NameValue = document.forms["FormName"]["nameValidation"].value;
</script>
</form>
I want the var NameValue to be the value of what you type into the input field so I can use it in the message which appears after the validation. When I change the value of the input field without submitting the form, the var NameValue is stil set to "HelloWorld". After doing some research I found out I could solve it using jQuery and it's function serialize(). Is there a way to do this without jQuery?
Without jQuery :
var value = document.getElementById('nameValidation').value;
The syntax you had would be usable to get an input by its name, not its id.
If what you want is to use this value when it changes, you can do that :
var nameValidationInput = document.getElementById('nameValidation');
function useValue() {
var NameValue = nameValidationInput.value;
// use it
alert(NameValue); // just to show the new value
}
nameValidationInput.onchange = useValue;
nameValidationInput.onblur = useValue;
Your code works. It assign value of your input field to var NameValue. What you explained and what JQuery serialize does are two different things.
Everything you need is to assign your code to right event:
<form name="FormName" method="post" />
<input type="text" id="nameValidation" value="HelloWorld" onchange="myFunction()"/>
</form>
<script type="text/javascript">
function myFunction(){
var NameValue = document.forms["FormName"]["nameValidation"].value;
alert(NameValue);
}
</script>
​see the JSFiddle.
use the onchange or onblur event to call this code:
var NameValue = document.forms["FormName"]["nameValidation"].value;
This way it will get activated when the cursor leaves the textbox
<input type="text" id="nameValidation" value="HelloWorld" onblur="changeVal();" />
<script type="text/javascript">
function changeVal() {
var NameValue = document.forms["FormName"]["nameValidation"].value;
alert(NameValue);
}
</script>
In your example, the variable only gets the value assigned to it at that moment in time. It does not update when the textbox updates. You need to trigger a function [onchange or onblur or keypress] and reset the variable to the new value.
<form name="FormName" method="post" />
<input type="text" id="nameValidation" value="HelloWorld" />
<script type="text/javascript">
var myTextbox = document.getElementById("nameValidation");
var nameValue = myTextbox.value;
myTextbox.onchange = function() {
nameValue = myTextbox.value;
};
</script>
</form>
You can let your client-side code respond to a change in the value of the textbox, like so:
$(document).ready(function(){
$("#nameValidation").on('change', function() {
var value = $("#nameValidation").value;
//do your work here
}
})

jQuery (or just JS) choosing from multiple form submit buttons in onSubmit function

I've got a form that has multiple submit buttons. One for changing data in a database, one for adding, and one for deleting. It looks like this:
<form action="addform.php" method="post" id="addform" onSubmit="return validate(this)">
<select name="listings" id="listings" size="1" onChange="javascript:updateForm()">
<!-- Here I have a php code that produces the listing menu based on a database query-->
</select>
<br />
Price: <input type="text" name="price" id="price" value="0"/><br />
Remarks: <textarea name="remarks" wrap="soft" id="remarks"></textarea><br />
<input type="submit" value="Update Database Listing" name="upbtn" id="upbtn" disabled="disabled"/>
<input type="submit" value="Delete Database Listing" name="delbtn" id="delbtn" disabled="disabled"/>
<br />
<input type="submit" value="Add Listing to Database" name="dbbtn" id="dbbtn"/>
<input type="button" value="Update Craigslist Output" name="clbtn" id="clbtn" onClick="javascript:updatePreview();"/>
</form>
There are actually more elements in the form, but that doesn't matter. What I want to know is, for my validation method, how can I check which submit button has been clicked?
I want it to do the following:
function validate(form){
if (the 'add new listing' or 'update listing' button was clicked'){
var valid = "Are you sure the following information is correct?" + '\\n';
valid += "\\nPrice: $";
valid += form.price.value;
valid += "\\nRemarks: ";
valid += form.remarks.value;
return confirm(valid);}
else {
return confirm("are you sure you want to delete that listing");
}
}
I assume there must be some way to do this relatively easily?
Why don't you set a global variable specifying which button was last clicked? Then you can check this variable in your validate method. Something like:
var clicked;
$("#upbtn").click(function() {clicked = 'update'});
// $("#delbtn").click(function() {clicked = 'delete'});
// ...
function validate(form) {
switch(clicked) {
case 'update':
break;
// more cases here ...
}
}
You can, for example, attach a click event to every submit button that will save a pointer to it in a variable or mark it with a specific attribute / class (it that case you will have to remove that marker from all other submit buttons in the event handler) and then in the submit callback you will know which one was clicked
I think it's easier to just use a click event on each button and handle it individually.
$(function() {
$('input[name=someName]').click(someFunc);
});
function someFunc() {
// Your validation code here
// return false if you want to stop the form submission
}
You could have a hidden field on a form and set the value of that field on clicking the button and then pick it up in your validation routine. You can use jquery to achieve this, let me know if you require an example.
You can use ajax submission with jQuery, you can try something like this:
$('form#addform input[type="submit"]').on('click',function(e){
e.preventDefault();
var current = $(this); //You got here the current clicked button
var form = current.parents('form');
$.ajax({
url:form.attr('action'),
type:form.attr('method'),
data:form.serialize(),
success:function(resp){
//Do crazy stuff here
}
});
});

Categories