I am using XHTML, JSF and JavaScript to create a form, validate that information has been submitted into selected fields onclick in a h:commandButton, and if validated, redirect to a different page homepage.xhtml. Everything works up to the redirection, which I can't get to work.
In the JavaScript function Validation(), I have tried location="homepage.xhtml", window.location.href="homepage.xhtml", location.url="homepage.xhtml" and a few others, but nothing seems to work. I have a feeling I'm supposed to have some sort of statement which adds href="homepage.xhtml" to the h:commandButton if Validate() returns true, but I am unsure as to how to do that.
Any help is greatly appreciated. I have added the relevant code below.
Button:
<h:commandButton class="btn btn-warning" value="Continue" onclick="Validation()"/>
Validation
function Validation() {
var nameCheck = document.getElementById('formdiv:cardName');
var numCheck = document.getElementById('formdiv:cardNumber');
var expCheck = document.getElementById('formdiv:expDate');
console.log(nameCheck.value);
console.log(numCheck.value);
console.log(expCheck.value);
var variablesToCheck = [nameCheck, numCheck, expCheck];
for(i=0; i < variablesToCheck.length; i++){
if(variablesToCheck[i].value == null || variablesToCheck[i].value == ""){
alert("Fields marked with a * must be completed");
return false;
}
}
// This is where the redirection needs to go, I think...
return true;
}
EDIT: Just noticed the if else statement is incorrect logically, but syntactically it shouldn't make a difference. The else part needs to be a statement outside of the loop without a condition; this code simply tries to redirect when the field it is checking has something in, not when all fields have something in.
EDIT 2: Loop corrected
Why you need h:commandButton anyway you are using simple javascript validation
h:commandButton is rendered as <input type="submit" ../> its mission is
to submit the form so what ever javascript you are writing your form will be submitted and your page is gonna be refreshed, So If you need it this way you have to force it not to submit the form,
However from understanding your needs all you need is simple <a /> or <button /> , Or you can just add type="button" into your h:commandButton ex:<h:commandButton type="button" .../>
You can either use..
window.location.replace('Your_url'); ..
or you can use..
window.location.href= 'Your_url'; .. I guess there must be other functions too. If you want to open it in another window, like a popup, you can use.. window.open('your_url');
Hope this helps!
Related
My alert divs don't show up when I click the submit button.
An 'Error' div should alert when there's an empty required field and,
a 'Success' div should alert right before the form submits. The form submits so I know the validation check works but, I don't see any of my alert divs. See code below:
const goaForm = document.getElementById('goa-form');
let formCompleted = $.trim($('#goa-form input[required]').val()) == !'';
let formIncomplete = $.trim($('#goa-form input[required]').val()) == '';
let success = document.getElementById('success-msg');
let error = document.getElementById('error-msg');
let submitButton = document.getElementById("btnSubmit");
function checkForm() {
if (formCompleted) {
success.style.visibility = 'visible';
goaForm.submit();
} else if (formIncomplete) {
error.style.visibility = 'visible';
$("#error-msg").fadeOut(28000);
return false;
}
}
submitButton.addEventListener("click", checkForm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="error-msg" style="visibility: hidden;" class="alert alert-danger" role="alert">
<span class="fs-14">Error message div</span></div>
<div id="success-msg" style="visibility: hidden;" class="alert alert-success" role="alert">
<span class="fs-15">Success!</span></div>
// Submit Button
<button onclick="checkForm()" id="btnSubmit" class="btn btn-success lift d-flex align-items-
center" type="submit">Submit my application <i class="fe fe-arrow-right ml-5"></i>
</button>
Thanks for the help guys.
checkForm() is fired when your button is clicked, but it uses values (formCompleted, formIncomplete) defined earlier, on page load. So you may fill out your form, but those variables are not updated, and clicking the button uses the old values that were set when the page was first loaded.
Instead, check the input states and define those variables inside your checkForm() function, so that they are set up as the actual, current results when the button is clicked. Then the tests evaluate what the form looks like at the time of the button click.
function checkForm() {
let formCompleted = $.trim($('#goa-form input[required]').val()) == !'';
let formIncomplete = $.trim($('#goa-form input[required]').val()) == '';
// ... rest of your code ...
Update
Here's a working JSFiddle.
Notes:
You're using a mix of plain JS and jQuery. There's nothing technically wrong with that, but it would certainly be easier to read and maintain if you stuck to one. If you are going to take the hit in loading jQuery (extra http request, 90kb odd extra resource, etc) you may as well use it.
I am not sure if it is actually invalid, but the formCompleted test seems wrong. I'd use the standard !== '' instead of == !'' (I've done that in the JSFiddle);
If you're going to use the type comparison for formCompleted, you should be consistent and also use it for formIncomplete, ie use === '' (I've done that in the JSFiddle);
Don't use both an inline onClick() on the button, and add an addEventListener in your JS. They both do the same thing, use only one of them. It is considered bad practice to mix JS in with your HTML, so using the plain JS addEventListener (or jQuery .on()) is better. I've removed the inline one from the JSFiddle.
Onclick of button,(In clientclick event)I show confrmation box having ok and cancel button.Onclick of ok button,buttonclick event fire.I want to disable button and show to message(Pls wait) to user.I am trying but not working.Unable to disable the button and set text to label.
function validate()
{
var response = confirm(Proceed)
if(response)
{
document.getElementById('btnSave').disabled = true;
document.getElementById('lblMessage').innerText = 'Please Wait';
return true;
}
else
{
return false;
}
}
I am getting error.Error is
JavaScript runtime error: Unable to get property 'innerText' of undefined or null reference in asp.net
First of all there's maybe a problem in your HTML. Javascript cannot find the 'lblMessage' element. Fix that first and you're good to go.
Maybe you're using ASP.NET Web Forms. ASP.NET changes the client ID's of server controls depending on the ID of their container. You can change this behavior easily by reading this article:
http://weblog.west-wind.com/posts/2009/Nov/07/ClientIDMode-in-ASPNET-40
Or, find your elements by class name. That way it won't cause conflict with any configuration you're now using.
I think you need to add your html code. I'm guessing your html looks like this
<button onclick="validate()">
you need to add a return statement into the html code so it looks like this
<button onclick="return validate()">
I have written some simple javascript to change the content of an iframe according to the input of a field. After hours of attempts, I have managed to get it working; however I didn't really understand why I should put the "return true" and "return false" at the end of my search function. Thank you in advance!
function search(){
var course=document.getElementById("field");
if(course.value!=""){
if(course.value!="Course code (e.g. COMP1004)"){
var target=document.getElementById("frame");
target.src=course.value + ".php";
return false;
}
}else{
return true;
}
}
<input id="field" name="field" type="text"></input>
<input id="searchButton" name="searchButton" type="button"value="Search"onclick="search()"></input>
You don't really need to, since you are calling the function without expecting any value. And even if you write onclick = return search() you have no default action to prevent, since your input has type="button"
When you trigger a javascript function using onclick (depending on the browser), the actual functionality of the click can be prevented by returning false. So if you click on a button and return true (or nothing) the actual click will be triggered and e.g. load a new page. If you return false, the original function of the button will not be called ...
jsfiddle demo
Bear with me, total newb here.
I'm trying to make a simple multiplication calculator, as a experimentation with Javascript.
The catch is that -
No libraries, just pure javascript.
Javascript must be unobtrusive.
Now, the problem arises, that it doesn't give the value out.
When I do this locally, answer has a value of NaN, and if you hit Submit it stays that way, BUT, if you press the back button, you see the actual result.
In the JSFiddle, much is not shown, except for the fact that it simply doesn't work.
Please tell me, is it even possible to make an unobtrusive calculator? How?
(PS. I was taking a bit of help from sciencebuddies, just to see basic syntax and stuff, but I found it can't be done without code being obtrusive)
I realize you're probably just getting started and don't know what to include, remove, and whatnot. But, good advice here, clearly label your elements so you can understand them, and pare it down to the smallest possible code you need for it to work (even less, so you can build it up).
Here is your code reworked:
HTML
<div>
<input type="text" id="multiplicand" value="4">
<input type="text" id="multiplier" value="10">
<button type="button" id="multiply">Multiply</button>
</div>
<p id="result">
The product is: <span id="product"> </span>
</p>
Javascript
window.onload = function(){
var button = el('multiply'),
multiplicand = el('multiplicand'),
multiplier = el('multiplier'),
product = el('product');
function el(id) {
return document.getElementById(id);
};
function multiply() {
var x = parseFloat(multiplicand.value) || 0,
y = parseFloat(multiplier.value) || 0;
product.innerHTML = x * y;
}
button.onclick = multiply;
};
http://jsfiddle.net/userdude/EptAN/6/
A slightly more sophisticated approach, with add/subtract/multiply/divide:
http://jsfiddle.net/userdude/EptAN/9/
You have to change the submit button so that it doesn't submit the form. Right now clicking "Submit" causes the form submits to the same page which involves a page reload.
Change the <input type="submit" id="submitt"> to <button type=button> and it should work.
You can probably do without the <form> element in the first place. That'll stop clicking enter in your text input from reloading the page.
Your example has a couple of problems:
The form still submits. After the JS changes the value, the submit will cause the page to reload, and that work you've done setting the answer value is wasted.
You're trying to do this stuff right away. In the header, none of the body has been parsed yet (and thus, the form elements don't even exist). You'll want to wait til the page is loaded.
The script hijacks window.onload. If you don't have any other scripts on the page, that's fine...but the whole point of unobtrusive JS (IMO) is that nothing breaks whether the script is there or not.
Fixed, we have something kinda like:
// Wrap this onload in an IIFE that we pass the old onload to, so we can
// let it run too (rather than just replacing it)
(function(old_onload) {
// attach this code to onload, so it'll run after everything exists
window.onload = function(event) {
// run the previous onload
if (old_onload) old_onload.call(window, event);
document.getElementById('Xintox').onsubmit = function() {
var multiplier = +this.multiplier.value;
var multiplicand = +this.multiplicand.value;
this.answer.value = multiplier * multiplicand;
return false; // keep the form from submitting
};
};
})(window.onload);
Note i'm attaching the meat code to the form, rather than the button, because hitting Enter in either of the factor boxes will trigger a submit as well. You could still attach to the button if you wanted, and just add a submit handler that returns false. But IMO it's better this way -- that way the form works just the same with JS as without (assuming the script on the server fills in the boxes appropriately), except it won't require a round trip to the server.
I have some form buttons
<input type="button" onclick="send_away('700302','update_item','0',2)" value="Change Quantity">
and they are calling the functions below: (different buttons call different functions from this script, which is embedded in the HTML file.
<script language="javascript" type="text/javascript">
function send_away(item_c,request_c,change_item_c,quantity_c){
form_c.item.value = item_c;
form_c.request.value = request_c;
form_c.change_item.value = change_item_c;
form_c.quantity.value = quantity_c;
form_c.submit();
}
//sends the form later
function later(){
address.incoming_address.value = 'l';
address.submit();
}
function address_now(){
form_c.incoming_address.value = 'n';
form_c.submit();
}
function remove_item(item_num){
form_c.removal.value = item_num;
form_c.submit();
}
</script>
The problem is, not one of these buttons works in firefox. They all work in every other browser I've tried.
Has anyone run into this kind of problem / know what I could be doing wrong? I've stared at it for a while and can't see anything, other than that my HTML doesn't validate very well, I don't have nearly time to fix all the validation problems though.
You can see the effect at http://www.terra-cotta-pendants.com/ - click a product and add it to cart - the buttons are on the cart page.
Thanks for any help.
add id="form_c" to your form and use document.getElementById('form_c') instead of just form_c
another option would be to access the form by using document.forms.form_c, but I have always preferred using id's