passing old value back to javabean from javascript - javascript

I have this piece of javascript:
<script type="text/javascript">
function show_confirm()
{
var type = '<%= nameBean.getTxnType() %>';
var old_cd = '<%= nameBean.getCode() %>';
var new_cd = document.getElementById("tbCode").value;
var cd;
if (type == "Update")
{
if(old_cd != new_cd)
{
var response = confirm("Code already exists. Do you want to replace it?");
if (response){
document.NameUpdate.submit();
}
else{
cd = old_cd;
}
}
</script>
and this is what i am doing in my jsp page to invoke this script:
<INPUT TYPE=SUBMIT NAME="action" onclick="show_confirm()" VALUE="Save Changes">
Its working fine when I hit ok.. but my question is how can i pass the value of old_cd back to the bean so it wont update it with the new code that was entered by the user in the tbcode box.. when user hit cancel i want to ignore what value was entered in textbox and not to update that field in database

I'm not entirely clear on the use case here, but here are a couple of answers:
If the question is, "how do I stop the form from submitting when the user hits cancel?", then the answer is, return false in the click handler:
if (response){
document.NameUpdate.submit();
}
else{
cd = old_cd;
return false;
}
If you need to submit the form no matter which one the user clicks, then you probably need to submit the old value in a hidden input field and have a way to tell the server that user hit "cancel" (probably another hidden field), e.g.:
<!-- html -->
<input type="hidden" name="old_cd" value="<%= nameBean.getCode() %>">
<input type="hidden" id="canceled" name="canceled" value="0">
and javascript:
// js snippet
if (response){
document.NameUpdate.submit();
}
else{
document.getElementById("canceled").value = 1;
return true;
}

Related

woocommerce POSTing data before javascript (jQuery) finishes

i have a custom gateway (which works perfectly), the problem is when a customer buys something for the first time, there is some token than needs to be generated with the card info, the thing is that just before that token is generated, the form tries to submit, but an error is displayed saying that "the object could not be found", so, no refresh and nothing, if i press again the submit button (or "place order" button) everything works!.
i believe that by that second time, the token is generated and in the corresponding hidden field:
here is my code, hope somebody could help me :S
HTML (from the chrome inspector):
<input type="hidden" name="card-name" data-conekta="card[name]">
<input type="hidden" name="exp-month" data-conekta="card[exp_month]">
<input type="hidden" name="exp-year" data-conekta="card[exp_year]">
<input type="hidden" name="conektaTokenId" value="">
<input type="hidden" name="conektaCustId" value="false">
Javascript
jQuery(window).load(function() {
var form;
var first_name;
var last_name;
var cvc;
jQuery('form[name="checkout"]').submit(function(event) {
jQueryform = jQuery(this);
Conekta.setPublishableKey(jQuery('input[name="pbkey"]').val());
console.log('entro');
if( jQuery('input[name="conektaCustId"]').val()=="true" && jQuery('input[name="conektaTokenId"]').val().substr(0,4)!="tok_"){
console.log('entro');
first_name = jQuery('#billing_first_name').val();
last_name = ' ' + jQuery('#billing_last_name').val();
expiry = jQuery('#conekta_card-card-expiry').val().replace(/ /g, '').split("/");
jQuery('input[name="card-name"]').val( first_name + last_name );
jQuery('input[name="exp-month"]').val( Number(expiry[0]));
jQuery('input[name="exp-year"]').val( Number(expiry[1]));
jQueryform.prepend('<span class="card-errors"></span>');
Conekta.token.create(jQueryform, conektaSuccessResponseHandler, conektaErrorResponseHandler);
woocommerce_order_button_html
return false;
}
else{
return;
}
});
var conektaSuccessResponseHandler= function(response){
var token_id = response.id;
jQuery('input[name="conektaTokenId"]').val(token_id);
}
var conektaErrorResponseHandler= function(response){
jQueryform.find('.card-errors').text(response.message);
}
});
i have found the solution, you have to add the class processing to the checkout form and just when you finished procesing your data to be send to wherever you need to (usually wordpress/woocommerce), remove that class so the form can submit the new data.

make a field mandatory using javascript

I am trying to make a select field mandatory on a web page. I know how to do it with help of JS and form attribute 'onsubmit' and returning the function. But the problem is that form code is already written and I dont know how to add attribute now. Let me know if I can append attribute dynamically from JS.
The other way I tried is to call the JS after page loaded. But this isnt making the field mandatory and form can be submitted.
Following is my code..
<!DOCTYPE html>
<html>
<head>
<script>
function f1()
{
var countryValue = document.getElementById('count ID').value;
if (countryValue == "")
{
alert("field value missing");
return false;
}
var stateValue = document.getElementById('state ID').value;
if (stateValue == "")
{
alert("state field value missing");
return false;
}
}
</script>
</head>
<body>
<form method = "post" action = "33.html">
Country: <input type="text" id="count ID">
state: <select id="state ID">
<option></option>
<option value="ap">ap</option>
<option value="bp">bp</option>
</select>
<br>
<input type = "submit">
</form>
<script>window.onload=f1</script>
</body>
</html>
Please help.
Have a look at this since you have messed up the IDs
Live Demo
window.onload=function() {
document.forms[0].onsubmit=function() { // first form on page
var countryValue = this.elements[0].value; // first field in form
if (countryValue == "") {
alert("Please enter a country");
return false;
}
var stateIdx = this.elements[1].selectedIndex; // second field
if (stateIdx < 1) { // your first option does not have a value
alert("Please select a state");
return false;
}
return true; // allow submission
}
}
PS: It is likely that POSTing to an html page will give you an error
To get the last button to do the submission
window.onload=function() {
var form = document.forms[0]; // first form
// last element in form:
form.elements[form.elements.length-1].onclick=function() {
...
...
...
this.form.submit(); // instead of return true
}
}
Once you've got a function to detect improper values (empty mandatory field or anything else, like a bad e-mail address for instance) you have a few different options :
disable the submit button
cancel the onclick event on the button
cancel the submit event on the form
disabling the submit button can be annoying for the user (it might flash on and off while the values are entered).
I had the same issue, but i made a extension. Using hook system to translate fields with "*", in the names, to validate like required field. This is a simple solution not intrusive where is not required addition of fields in the database, only by the use of sufix "*" in configuration of custom fields.
There is the code: https://github.com/voiski/bugzilla-required-field

How to ensure my confirm checkbox is ticked before allowing submission of my form

Once again the novice JS is back again with a question. I want a confirmation tickbox at the end of my form before allowing the user to send me their details and if it's not ticked then they can't submit the form. I've had a look on here and tried using different examples of coding but I just find it all very confusing after looking at 10 or 20 pages of different code. Here is what I've written so far, from what I can make out my form just skips over my checkbox validation code which is obviously what I don't want to happen:
<head>
<script>
function validate (){
send = document.getElementById("confirm").value;
errors = "";
if (send.checked == false){
errors += "Please tick the checkbox as confirmation your details are correct \n";
} else if (errors == ""){
alert ("Your details are being sent)
} else {
alert(errors);
}
}
</script>
</head>
<body>
<div>
<label for="confirm" class="fixedwidth">Yes I confirm all my details are correct</label>
<input type="checkbox" name="confirm" id="confirm"/>
</div>
<div class="button">
<input type="submit" value="SUBMIT" onclick="validate()"/>
</div>
I would just enable/disable your button based on the checkbox state. Add an ID to your button, (i'll pretend the submit button has an id of btnSubmit)
document.getElementById("confirm").onchange = function() {
document.getElementById("btnSubmit").disabled = !this.checked;
}
Demo: http://jsfiddle.net/tymeJV/hQ8hF/1
you are making send be confirm's value.
send = document.getElementById("confirm").value;
This way send.checked will not work. Because you are trying to get the attribute checked from a value (probably, string).
For the correct use, try this:
send = document.getElementById("confirm");
sendValue = send.value;
sendCheck = send.checked;
Then you can test with
if (sendCheck == false){ //sendCheck evaluate true if checkbox is checked, false if not.
To stop form from submitting, return false; after the error alerts.
Here the complete code - updated to work correctly (considering the <form> tag has id tesForm):
document.getElementById("testForm").onsubmit = function () {
var send = document.getElementById("confirm"),
sendValue = send.value,
sendCheck = send.checked,
errors = "";
//validate checkbox
if (!sendCheck) {
errors += "Please tick the checkbox as confirmation your details are correct \n";
}
//validate other stuff here
//in case you added more error types above
//stacked all errors and in the end, show them
if (errors != "") {
alert(errors);
return false; //if return, below code will not run
}
//passed all validations, then it's ok
alert("Your details are being sent"); // <- had a missing " after sent.
return true; //will submit
}
Fiddle: http://jsfiddle.net/RaphaelDDL/gHNAf/
You don't need javascript to do this. All modern browsers have native form validation built in. If you mark the checkbox as required, the form will not submit unless it is checked.
<form>
<input type="checkbox" required=""/>
<button type="submit">Done</button>
</form>

Create URL upon JavaScript submit form

I currently have a form with some JavaScript functions and localstorage.
I'm trying to get that when a user types a value into a textbox, the search bar changes the URL from "mysite.com" to "mysite.com/%userinput%". Then that user can send that link to someone else and that person will then see what the original user saw.
This will change the URL after input.
As I understand from your question and comments, you don't want to load the URL, just change it, so try this fiddle: http://jsfiddle.net/GrP6U/2/show/
The code behind is:
JavaScript
var theForm = document.getElementById('theForm');
var theInput = document.getElementById('subj');
theForm.onsubmit = function(e) {
var myurl = "http://jsfiddle.net/GrP6U/2/show/?input=" + encodeURIComponent(theInput.value);
window.history.pushState('', "Title", myurl);
return false;
}
HTML
<form id="theForm">
<input id='subj'/>
<input type='submit'/>
</form>

javascript - why doesnt this work?

<form method="post" action="sendmail.php" name="Email_form">
Message ID <input type="text" name="message_id" /><br/><br/>
Aggressive conduct <input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct <input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct <input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct <input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" onclick=validate() />
</form>
window.onload = init;
function init()
{
document.forms["Email_form"].onsubmit = function()
{
validate();
return false;
};
}
function validate()
{
var form = document.forms["Email_form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") { //No value in the "message_id"
box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
}
</script>
Am i missing something or am i just being stupid?
edit***
sorry i should add! the problem is that i want the javascript to stop users going to 'sendmail.php' if they have not entered a message id and clicked a radio button... at the moment this does not do this and sends blank emails if nothing is inputted
You are using
validate();
return false;
...which means that the submit event handler always returns false, and always fails to submit. You need to use this instead:
return validate();
Also, where you use document.forms["Email form"] the space should be an underscore.
Here's a completely rewritten example that uses modern, standards-compliant, organised code, and works:
http://jsbin.com/eqozah/3
Note that a successful submission of the form will take you to 'sendmail.php', which doesn't actually exist on the jsbin.com server, and you'll get an error, but you know what I mean.
Here is an updated version that dumbs down the methods used so that it works with Internet Explorer, as well as includes radio button validation:
http://jsbin.com/eqozah/5
You forgot the underscore when identifying the form:
document.forms["Email_form"].onsubmit = ...
EDIT:
document.forms["Email_form"].onsubmit = function() {
return validate();
};
function validate() {
var form = document.forms["Email_form"];
if (form.elements["message_id"].value == "") {
alert("Enter Message Id");
return false;
}
var conduct = form.elements['conduct']; //Grab radio buttons
var conductValue; //Store the selected value
for (var i = 0; i<conduct.length; i++) { //Loop through the list and find selected value
if(conduct[i].checked) { conductValue = conduct[i].value } //Store it
}
if (conductValue == undefined) { //Check to make sure we have a value, otherwise fail and alert the user
alert("Enter Conduct");
return false;
}
return true;
}
return the value of validate. Validate should return true if your validation succeeds, and false otherwise. If the onsubmit function returns false, the page won't change.
EDIT: Added code to check the radio button. You should consider using a javascript framework to make your life easier. Also, you should remove the onclick attribute from your submit input button as validation should be handled in the submit even, not the button's click
Most obvious error, your form has name attribute 'Email_form', but in your Javascript you reference document.forms["Email form"]. The ironic thing is, you even have a comment in there not to use spaces in your form names :)

Categories

Resources