jsp pass variables between two pages - javascript

In my main jsp page, I have something like
<%# include file="../customParametersHorizontal.jsp" %>
<tr>
<td align="center" class="ReportParamsGenerateButtonCell">
<html:submit onclick="if(preGenerateCriteria()){return true;} else {return false;}">Generate</html:submit>
</td>
</tr>
Within customParametersHorizontal.jsp, there is another include for dateSelection1.jsp, which validates date and time set on the form.
<script>
function validateHHMM(inputField, message) {
var isValid = /^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/.test(inputField);
if (isValid) {
}else {
alert("Time must be entered in the format HH:MM AM/PM");
}
return isValid;
}
</script>
So, within dateSelection1.jsp, I tried to disable the button in the main jsp using :
document.form1.ReportParamsGenerateButtonCell.disabled= true;
But, I get an error saying object is null or not defined.
Is there anyway, I can set a var, so that it can be chacked by the main form and disable the button accordingly?

Here's a way to do it, retaining the <html:submit> tag, and without introducing jQuery: First, add the styleId attribute so that your button has an HTML ID you can grab onto:
<html:submit styleId="my_submit" onclick="if(preGenerateCriteria()){return true;} else {return false;}">Generate</html:submit>
Next, use the ID to get the element of the DOM and disable it:
var elt = document.getElementById("my_submit");
elt.disabled = true;
Update
If I understand the original question correctly, main.jsp includes customParametersHorizontal.jsp, whici includes dateSelection1.jsp. So the three scripts are rendering just one HTML page, hence one document object.
I only see (partial) code for one <form> on the HTML page. Even if you do have more than one form, .getElementById() works across all DOM elements in all forms, as opposed to the document.form1 style of accessing elements.
Be sure that you call validateHHMM() at the appropriate point to enable/disable your submit button, and make sure that the button is re-enabled once the user corrects his input to make it valid.

document.form1.ReportParamsGenerateButtonCell will return null or error unless you have the elements with name attribute set to form1 and ReportParamsGenerateButtonCell like the example bellow:
<form name="form1">
<input type="submit" name="ReportParamsGenerateButton" value="Generate" />
</form>
This way you could do document.form1.ReportParamsGenerateButton.disabled = true without problem.

Related

Dynamically changing form action not working for MailChimp

I am using a checkbox to change the form action on a MailChimp-form dynamically. When the DOM is loaded, the form action URL is something like this:
https://X.us3.list-manage.com/subscribe/post?u=X&id=X&EBIRD=XYZ
When I submit the form, the EBIRD-value of XYZ is pushed to MailChimp. Now, when I check the checkbox, I can see from the DOM and my console that the new form action is this:
https://X.us3.list-manage.com/subscribe/post?u=X&id=X&EBIRD=NEW-VALUE
Why is it then, that submitting the form still pushes XYZ and not NEW-VALUE? I have been in touch with MailChimp technical support. They said that when choosing "View Source" on the page, the old value was still there. But isn't that just because that is how the page is loaded in the first place?
Relevant HTML:
<form action="https://X.us3.list-manage.com/subscribe/post?u=X&id=X&EBIRD=XYZ" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
Relevant jQuery:
var formActionYes = "https://X.us3.list-manage.com/subscribe/post?u=X&id=X&EBIRD=NEW-VALUE";
var formActionNo = "https://X.us3.list-manage.com/subscribe/post?u=X&id=X&EBIRD=NEW-VALUE-2";
$('#cu-ebird').change(function() {
if(this.checked) {
$("#mc-embedded-subscribe-form").prop('action',formActionYes);
console.log($("#mc-embedded-subscribe-form").prop('action'));
} else {
$("#mc-embedded-subscribe-form").prop('action',formActionNo);
console.log($("#mc-embedded-subscribe-form").prop('action'));
}
});
The console logs what I want. The DOM shows what I want. MailChimp recieves the old value.
What am I missing?
Don't use HTML entities like & in JavaScript strings. That's only processed in HTML code, not when properties are assigned in JavaScript.
var formActionYes = "https://X.us3.list-manage.com/subscribe/post?u=X&id=X&EBIRD=NEW-VALUE";
var formActionNo = "https://X.us3.list-manage.com/subscribe/post?u=X&id=X&EBIRD=NEW-VALUE-2";
Although I'm not sure why this would impact the EBIRD parameter. It should cause the id parameter to be renamed to amp;id.
Another thing you could try is using .attr() rather than .prop().
This can be solved by not trying to change the form action at all. Just remove the merge field from the form action. Instead, you need to add a hidden input field to your form:
<input id="ebird" type="hidden" name="EBIRD" value="">
Then you change the value of this using the script:
$("#ebird").attr('value','NEW-VALUE');
Voila, everything shows up in MailChimp as it should.

JS Ajax OnClick: How to execute php code multiple times?

I have an html button with an onclick attribute which runs a jQuery AJAX function pointing to php code.
The php code writes HTML in an output HTML <select> element(the element remains hidden until the javascript runs.)
This is working great to populate the <select> when an "add another" button is clicked.
The problem is it adds one and only one. I want to be able to have a new <select> tag populate with each click of the "add another" button up to a max of 2.
The JS in question:
var genre_dropdown = function genre_dropdown() {
$('.genre_output').css('display', 'block');
$.ajax({
url:'../includes/functions/genre_dropdown.php',
complete: function (response) {
$('.genre_output').html(response.responseText);
},
error: function () {
$('.genre_output').html('Bummer: there was an error!');
}
});
return false;
}
The HTML in question:
<select name="genre_id[]" autocomplete="off" class="genre_output"></select>
<select name="genre_id[]" autocomplete="off" class="genre_output"></select>
<div class="button add-genre-button" onclick="return genre_dropdown();">+ Add Existing Genre</div>
I thought I could include 2 html <select> elements for the php to populate into, the code would execute from one to the next. I see why this is not correct, the code is running in both at the same time. I'm at a place where I'm considering have 2 buttons ("add one", "add another") but that seems redundant and not correct, especially considering I want a scale-able technique (the max may not always be 2.) I need help.
Your php request is fine.
I simply mean define a variable as your using javascript i.e.:
var sel = '<select name="genre_id[]" autocomplete="off" class="genre_output">' + response + "</select>';
and then each time you do a request it will include the response as the value of the element. This would allow you to append the parent div as many times as you want. Finally, use a simple if counter to decide whether to keep appending or not:
if ($(".genre_output").length <= 2){
$("PARENT_DIV_ID").append(sel);
};
Is this clearer? #kaari
Assuming you want to keep previous values in dropdown then you can try append() instead of html()
$('.genre_output').append(response.responseText);

trouble resetting form through javascript or jquery

I have the below jQuery function which is called when ever I click a button on my page. This button is supposed to reset the form and reload a fresh page.
function Create(txt) {
if (txt="createUser") {
document.forms[0].reset();
$('#myform').each(function() {
this.reset();
});
$('input[name=method]').val(txt);
document.forms[0].submit();
}
}
But for some reason, it does not go to this.reset() at all and I see all the form values in my action class. How should I solve this?
Below is how the button is defined.
<input type="button" value="Create" class="btn" onclick="Create('createUser');">
edit: Ok guys.. i know how input type="reset" works and i have another button in my page doing the same.. I have a create user form where i can search and see an existing user details or fill the form and create a new user. if i search for a user and then click on create to create another user, it sends a new request to the server and reloads the page.. but in the action class.. the bean has not been reset.. and i get all the values back on the page. hence ..i want to reset the form...without using the reset button...
I selected John's answer .. made a slight modification and below is the final function i used.
function Create(txt){
if (txt="createUser"){
var $form = $('#myform');
$form.find(':input').not(':button,:submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected'); // Clear all inputs
$form.find('input[name=method]').val(txt);
$form.submit();
}
}
Instead of java script, you can have html code,
<input type="reset" value="Reset">
As others have pointed out, you have = where you should have ==, but that means the if-statement is always true. It is not, however, the reason you "see all the form values in my action class".
I think the problem may be that you are misinterpreting what the reset() method does. It does not clear all the input values; instead, it resets them to their original values (i.e., the values in the "value" attributes).
You may want to clear them yourself, rather than use the reset() method.
function Create(txt) {
if (txt == 'createUser') {
var $form = $('#myform');
// Clear form values
$form.find(':input:not(:button,:submit,:reset,:checkbox,:radio,:hidden)').val('');
$form.find('input:checkbox,input:radio)').prop('checked', false);
$form.find('input[name=method]').val(txt);
$form.submit();
}
}
Note: The :input selector matches all input, textarea, select and button elements.
Note: It appears the OP does not want hidden inputs to be cleared, but does want checkboxes and radio buttons cleared.
You seem to be setting a variable here -
if (txt="createUser"){...
Change it to -
if (txt == "createUser") {..
That way you're doing a comparison, instead of setting a variable.
the button does not have type="reset" so either change it to reset or use
document.getElementById("myform").reset(); instead of
document.forms[0].reset();
$('#myform').each(function(){
this.reset();
});
I would do like this:
$(document).ready(function() {
$("#createUserButton").on("click", function() {
var form = $("#myForm")[0];
form.reset();
$("input[name=method]").val("CreateUser");
form.submit();
}
});
And your button becomes:
<input type="button" value="Create" class="btn" id="createUserButton">
I'd suggest you to place an id attribute as well in your input text, something like:
<input type="text" name="method" id="methodName" />
And then you could reference it by id which is faster than by name, like this:
$("#methodName").val("CreateUser");
Your code was wrong, in your if you should've used == or === instead of just = and your form should've just have called reset method. No need to iterate over an id using each, even because an ID have to be unique in an HTML page.
Here's a workin fiddle, just type something in the first input to see it happening.

Form onsubmit() does not function

I want to control my form for the required input texts, and I have made a function in javascript. But when I click the button, and I havent fill the required field nothing the message do not appear, and I can go to the other page.
the function is:
function Validate(){
// create array containing textbox elements
var inputs = [document.getElementById('firstname1')];
var error;
for(var i = 0; i<inputs.length; i++)
// loop through each element to see if value is empty
{
if(inputs[i].value == '')
{
error = 'Please complete all fields.';
alert(error);
return false;
}
}
}
and the part of form is:
<form name="password" onsubmit="return Validate()" method="post" id="password" action="#">
<input type="submit" value="Proceed" id="submit1" onclick="displayform2()" class="button" style=" margin-top: -40px;margin-left: 60%;width: 25%" disabled>
I have noticethat if I put off the onclick method in the button it works, but I should have this method at the button...How can I solve this?Please help me
function displayform2() {
/*For desktop*/
if (document.getElementById('desktop1').style.display=='block') {
document.getElementById('desktop1').style.display='none';
document.getElementById('desktop2').style.display='block';
document.getElementById('desktop3').style.display='none';
}
/*For mobile*/
if (document.getElementById('mobile1').style.display=='block') {
document.getElementById('mobile1').style.display='none';
document.getElementById('mobile2').style.display='block';
document.getElementById('mobile3').style.display='none';
}}
It opens another form in the page...so when I click the button the first form dissapeared and the second form is displayed
You have this: var inputs = [document.getElementById('firstname1')];
Then you try to loop through that. I'm betting firstname1 is a field, so it's either null (if that field doesn't exist) or an array with only one element (the field). It looks like you are trying to check all required fields, so that won't work.
I'm not 100% what you ultimately want to do, but it will likely be much easier if you use a framework like jQuery; otherwise, you are going to have to do some complicated case-handling for different browsers.
Nowhere in your code do you call submit. That is why the function in the onsubmit handler is not triggered. If you want the button to submit the form, it would need to be a submit button.
Your example is a little unclear. For example, you are trying to validate whether a value has been entered into the input "firstname1", but you don't have markup for that element in your HTML.
I suspect what you are trying to do is to validate whether the form has been filled out or not. Something like the following (which validates input "firstname1") will do the job:
$(document).on("click", "#submit1", function(){
if($("#firstname1").val() == "" || $("#firstname1").val() == null){
alert("Please complete all fields.");
}
});
Working example here
The above requires jQuery, but can also be converted into vanilla JavaScript.
Load the jQuery library in the "head" section of your document by including the following code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

"Bubble" validation message on non-form element

I have some elements on a page and I want to make use of the nice bubble style messages such as described here HTML5 form validation. It seems that to use them it is required they are within a form element and they only can be used on validation once the form is attempted to be submitted.
Taking from the linked example, I want to know how to get the following to work as described (i.e for this example pop a bubble message if the user sets a time before now)
Fiddle for this: My attempt without form
<body>
<label>
Arrival Date:
<input id="arrivalDate" type="date" onchange="dateChanged()" />
</label>
<input type="button" value="Test Reservation"></input>
<script type="text/javascript">
function dateChanged(e){
var arrivalDate = document.getElementById("arrivalDate");
var value = new Date(arrivalDate.value);
if (value < new Date()) {
arrivalDate.setCustomValidity("Arrival date must be after now!");
} else {
arrivalDate.setCustomValidity("");
}
arrivalDate.checkValidity();
}
</script>
</body>
Specifically in my case I have 2 KendoUI DateTimePickers being used to select the time range which is used to display information dynamically on the page. I'd like if I could use these bubble messages if the user tries to make the start time after the end time.
There's no way to manually trigger the validation. Using .checkValidity() will only return true/false if the context of what your checking is valid or not, i.e. if you did form.checkValidity() it will check if all form elements are valid, or input.checkValidity() only check the validity of that single element.
The only way to trigger the validation is on submit. You can simulate this by having a submit button and calling the click function.
if (!arrivalDate.checkValidity())
{
document.getElementById('submit_reservation').click();
}
Fiddle: http://jsfiddle.net/QGpQj/3/
Note: I've added window.dateChanged = .... because of your inline event listener. You really should be using .addEventListener or, ideally, jQuery for this to add backwards compatability support for those non-supported browsers.

Categories

Resources