This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
prevent postback of HtmlButton in C#
Here's my JavaScript function:
<script type = "text/javascript">
function CheckForEmptySearchBox(id) {
var index = id.substring(id.length - 1);
var boxContent = document.getElementById("contentMain__lvTSEntry__txtClientName_" + index).value;
if (boxContent == "") {
alert("Please enter search criteria");
return false;
}
}
</script>
And the markup:
<asp:Button ID="_btnSearch" runat="server" OnClientClick = "return CheckForEmptySearchBox(this.id)" />
This code is working, i.e. when the texbox is empty, the message prompt the user to enter search criteria and the javascript prevents the page to postback. However, when the user enters text, there's no message prompt but the page still doesn't postback. What's wrong?
EDIT
if (boxContent == "") {
alert("Please enter search criteria");
return false;
}
else {
return true;
}
The page is still not posting back.
you need to return true from your function if you mean it to return true....
<script type = "text/javascript">
function CheckForEmptySearchBox(id) {
var index = id.substring(id.length - 1);
var boxContent = document.getElementById("contentMain__lvTSEntry__txtClientName_" + index).value;
if (boxContent == "") {
alert("Please enter search criteria");
return false;
}
else{ return true;}
}
you are asking for a return onclientclick function and not returning any value when textbox having value that`s why its stuck
<asp:Button ID="_btnSearch" runat="server" OnClientClick = "return CheckForEmptySearchBox(this.id)" />
You are forgetting to return true if the validation passes:
function CheckForEmptySearchBox(id) {
var index = id.substring(id.length - 1);
var boxContent = document.getElementById("contentMain__lvTSEntry__txtClientName_" + index).value;
if (boxContent == "") {
alert("Please enter search criteria");
return false;
}
return true; //<--you forgot this
}
Related
Can someone help me out with validation of two text-box with same email Id.
I was able to pop an alert if both the text-box contain the same email Id via JavaScript(my requirement was both text-box cant have same email) but now I m facing a problem if second text box contain more then one email_Id separated my comma(,) the validation doesn't work.
I don't want email that is present in first text box repeat into second text-box.
My code:
<script language="javascript" type="text/javascript">
function validated() {
if (document.getElementById("<%=txtCountry.ClientID %>").value = document.getElementById("<%=txtnewViewer.ClientID %>").value) {
alert("Presenter cant be attende");
return false;
}Else{
return true;
}
}
</script>
check this code out
<script language="javascript" type="text/javascript">
function validated()
{
if (document.getElementById("<%=textbox1.id %>").value == document.getElementById("<%=textbox2.id %>").value)
{
alert("text-box cant have same email");
return false;
}
else
{
alert("Valid");
return true;
}
}
</script>
Can you try this.
var f_email = document.getElementById("f_email").value;
var s_email= document.getElementById("s_email").value;
if(f_email === s_email) {
// do something when email ids are same.
alert("email ids are same");
}
else {
// do something when email ids are same.
alert("email ids are not same");
}
First, you if statement contains an = who always return true and modify your variable (in place of ==).
function validated() {
var clientId = document.getElementById("<%=txtCountry.ClientID %>").value,
viewerId = document.getElementById("<%=txtnewViewer.ClientID %>").value;
if (clientId == viewerId) {
alert("Presenter cant be attende");
return false;
}
return true;
}
After that you can use : Array.indexOf():
var clients = clientId.split(","), viewers = viewerId.split(",");
// Here we have two arrays with all datas
for(var i = 0; i < clients.length; i++){
var k = viewers.indexOf(clients[i]);
if(k !== -1) {
alert(clients[i], "=", viewers[k]);
}
}
I have a textbox and a button, on button's clientClick I call javascript function and there is also server side coding.
Problem is, the page gets post back even if I have return False in the javascript.
Here is my javascript function:
function checkALphaNumericFormat(str) {
//get previous value before editing
var txtUserId = document.getElementById('<%=txtUserId.ClientID%>');
var userId = txtUserId.value;
var patternAlphaNumeric = /^[A-z0-9]+$/gi;
var match = userId.match(patternAlphaNumeric);
//Check Null values
if (txtUserId.value != null && txtUserId.value != "") {
//Check for AlphaNumeric values for User Id
if (match == null) {
alert("Please provide valid AlphaNumeric User Id");
return false ;
}
return false ;
}
else {
alert("User Id field should not be null");
return false ;
}
return false ;
}
and I am calling this function on my Form as:
<asp:Button runat="server" ID="btnCreate" CssClass="loginButton" style="margin:0px 0px 1px 30px;" OnClientClick ="return checkALphaNumericFormat(this.value);" Text="CREATE" />
Try to call JavaScript function as below:
OnClientClick="if(!validateform()){return false;}
where validateform() should be your java script function. Your java script function should have return = true; at the end of function in successfull execution, like in below function:
function validateform()
{
var txtSearch = document.getElementById('<%=txtKeywordSearch.ClientID%>')
if(txtSearch.value == '')
{
alert('No Search Creatria Selected!');
return false;
}
return true;
}
Please try and let me know if it works for you.
Thanks,
Harish
OK, i have a couple of inputs. I have this code to validate them.
$("#form1").submit(function(){
var isFormValid = true;
$("#first_name").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
}
});
if (!isFormValid) alert("Please Enter Your First Name");
return isFormValid;
});
$("#form1").submit(function(){
var isFormValid = true;
$("#last_name").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
}
});
if (!isFormValid) alert("Please Enter Your Last Name");
return isFormValid;
});
$("#form1").submit(function(){
var isFormValid = true;
$("#dropdown").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
}
});
if (!isFormValid) alert("Please Select Your Volunteer Choice");
return isFormValid;
});
For some reason, i get a message after a message. What i was aiming for is that it only show me the next field that has not been field out, not all of them at the same time. If you have a question, please comment, it is hard to explain....do not down vote until you give me a chance to better explain.
Here is how to simplify your code, and make it work like intended.
First, since you use the same method to validate all the fields, wrap that in a function instead of repeating the code:
function isFieldEmpty(jQuerySelector) {
return $.trim($(jQuerySelector).val()).length == 0
}
Second, use a single submit handler to check everything, and return false if any field does not pass validation:
$("#form1").submit(function(){
if(isFieldEmpty('#first_name')) {
alert("Please Enter Your First Name");
return false;
}
if(isFieldEmpty('#last_name')) {
alert("Please Enter Your Last Name");
return false;
}
if(isFieldEmpty('#dropdown')) {
alert("Please Select Your Volunteer Choice");
return false;
}
// Will return true only if all fields passed
return true;
});
I'm not familiar with JQuery but I think what is happening is your are binding 3 functions to your form, which means they all get called
when you want to do is create 1 function validate that calls your sub validations functions.
also I would recommend you change your sub validation methods to return the message instead of a boolean, this way you can display all the errors in 1 alert.
You have multiple alerts because you bind different functions to the submit event of the form: each one checks a different field and fires an alert if the field is empty.
You need to move the three validation steps in only one function and bind that function to the submit event.
Something like:
$("#form1").submit(check);
function check() {
var isFormValid = true;
var errors = array();
$("#first_name").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
errors.push("Please Enter Your First Name");
}
});
$("#last_name").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
errors.push("Please Enter Your Last Name");
}
});
$("#dropdown").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
errors.push("Please Select Your Volunteer Choice");
}
});
if (!isFormValid) {
var errorMsg = "";
for (var i = 0; i < errors.length; i++) {
errorMsg += errors[i] + "\n";
}
alert(errorMsg);
}
}
This is because of the redundancy on your code, same function, same identifier, same logic, same event handler, useless each with an id selector.
The only thing different are the subjects. Here is my suggestion.
$("#form1").submit(function(){
var errors = [];
if($("#first_name").val().length == 0){
errors.push("Please Enter Your First Name");
}
if($("#last_name").val().length == 0){
errors.push("Please Enter Your Last Name");
}
// and so on
if(var isFormValid = errors.length > 0) {
alert('you have errors');
//errors contains all the error message if you need them
}
return isFormValid;
});
I'm trying to setup a 'Click to Chat' system for my company. It requires a form which captures some information from the user. When you submit the form, it's supposed to open a new window using the script in the .js file.
I tried to add some validation, which resulted in both an onclick, and an onsubmit function. When the form is subitted without the validation in place, it opens a new window using the BG.startChatWithIssueForm(this.form, true); function. But, For some reason, when I include the onsubmit for validation, the onclick ignores it completely.
I've tried nesting the BG.startChatWithIssueForm(this.form, true); function in different spots in the formValidator() function, but it still results in a file download prompt instead of opening a new window.
Not sure what I'm doing wrong. I've been researching this for weeks, and can't seem to come up with anything. Javascript is definitely not my forte, so any assistance would be greatly appreciated.
See the code below:
JS:
function Bomgar() {
var _host = "";
var _protoRe = /^(http|https):\/\//;
/* private */
function _createURL(params, forPopup) {
var qStr = "";
for (var k in params) {
qStr += "&"+encodeURIComponent(k)+"="+encodeURIComponent(params[k]);
}
qStr = "popup="+(forPopup ? "1" : "0") + "&c2cjs=1" + qStr;
return _host+"api/start_session.ns?"+qStr;
};
function _openWindow(params) {
return window.open(_createURL(params, true), 'clickToChat', 'toolbar=no,directories=no,status=no,menubar=no,resizable=yes,location=no,scrollbars=no');
};
function _redirectWindow(params) {
window.location.href = _createURL(params, false);
};
function _startChat(params, doFull) {
var w = _openWindow(params);
if (w && !w.closed) { return; }
else if (doFull) { _redirectWindow(params); return; }
};
function _startChatWithSurveyValues(surveyValues, fallbackToFullWindow) {
surveyValues.issue_menu = '1';
_startChat(surveyValues, fallbackToFullWindow);
};
/* public */
// Set the public site hostname that click to chat should be started on.
this.setSite = function(siteHostname) {
if (!_protoRe.test(siteHostname)) { siteHostname = "http://"+siteHostname; }
if (siteHostname[siteHostname.length-1] != '/') { siteHostname += '/'; }
_host = siteHostname;
};
// Start a click to chat session using a session key, optionally falling back to a full browser window redirect if the popup window fails to open due to popup blockers.
this.startChatWithSessionKey = function(sessionKey, fallbackToFullWindow) {
var p = {short_key: sessionKey};
_startChat(p, fallbackToFullWindow);
};
// Start a click to chat session using a session key and external key, optionally falling back to a full browser window redirect if the popup window fails to open due to popup blockers.
this.startChatWithSessionKeyAndExternalKey = function(sessionKey, externalKey, fallbackToFullWindow) {
var p = {short_key: sessionKey, external_key: externalKey};
_startChat(p, fallbackToFullWindow);
};
// Start a click to chat session using just an issue id and no other front end survey fields.
this.startChatWithIssueId = function(issueId, fallbackToFullWindow) {
_startChatWithSurveyValues({id: issueId}, fallbackToFullWindow);
};
// Start a click to chat session by passing the entire front end survey form element.
// This will submit all non-button input element values on the form.
// Any unexpected survey field names will be ignored.
this.startChatWithIssueForm = function(formElement, fallbackToFullWindow) {
var params = {};
for (var i = 0; i < formElement.elements.length; i++) {
var e = formElement.elements[i];
if (e.name && e.value && e.type && e.type != 'button' && e.type != 'submit') {
params[e.name] = e.value;
}
}
formElement = undefined;
params.issue_menu = '1';
_startChat(params, fallbackToFullWindow);
return false;
};
// Start a session with a representative id and name.
this.startChatWithRepIdName = function(repId, repName, fallbackToFullWindow) {
var p = {id: repId, name: repName};
_startChat(p, fallbackToFullWindow);
};
return this;
}
var BG = Bomgar();
HTML Code:
<script type="text/javascript" src="https://***.******.com/api/clicktochat.js"></script>
<script type="text/javascript">
BG.setSite("https://***.******.com");
</script>
<script type='text/javascript'>
function formValidator(){
// Make quick references to our fields
var issueid = document.getElementById('issueid');
var username = document.getElementById('username');
var userid = document.getElementById('userid');
var issuedesc = document.getElementById('issuedesc');
// Check each input in the order that it appears in the form
if(madeSelection(issueid, "Please choose an issue"))
{
if(notEmpty(username, "Please enter your name"))
{
if(isAlphanumeric(username, "Numbers and Letters Only for name"))
{
if(notEmpty(userid, "Please enter your user ID"))
{
if(isAlphanumeric(userid, "Numbers and Letters Only for user ID"))
{
if(notEmpty(issuedesc, "Please type a description of your problem"))
{
}
}
}
}
}
}
}
//check to make sure user selected their issue
function madeSelection(elem, helperMsg){
if(elem.selectedIndex == 0 ){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}else{
return true;
}
}
//check to make sure user entered something in the particular field
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
//check to make sure user only entered numeric characters
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
//check to make sure user only entered alpha characters
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
//check to make sure user entered only alpha or numeric characters
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
</script>
<script type="text/javascript">
/***********************************************
* Disable "Enter" key in Form script- By Nurul Fadilah(nurul#REMOVETHISvolmedia.com)
* This notice must stay intact for use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
function handleEnter (field, event) {
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if (keyCode == 13) {
var i;
for (i = 0; i < field.form.elements.length; i++)
if (field == field.form.elements[i])
break;
i = (i + 1) % field.form.elements.length;
field.form.elements[i].focus();
return false;
}
else
return true;
}
</script>
<form action="https://***.******.com/api/start_session.ns" onsubmit="return formValidator();" method="get">
What issue are you having?
<select onkeypress="return handleEnter(this, event)" id="issueid" name="id">
<option value="">Choose</option>
<option value="1">I need help getting started</option>
<option value="2">I am receiving an error</option>
</select>
<br />
Your First and Last Name: <input onkeypress="return handleEnter(this, event)" type="text" id="username" name="customer_name" /><br />
Your User ID (ABC1234): <input onkeypress="return handleEnter(this, event)" type="text" id="userid" name="customer_id" /><br />
Describe Your Issue: <textarea onkeypress="return handleEnter(this, event)" id="issuedesc" name="customer_desc"></textarea><br />
<input onkeypress="return handleEnter(this, event)" type="hidden" name="issue_menu" value="1" />
<input onkeypress="return handleEnter(this, event)" type="submit" value="Submit" onclick="BG.startChatWithIssueForm(this.form, true); return false;" />
<br>
<input onkeypress="return handleEnter(this, event)" type="button" name="reset_form" value="Clear" onclick="this.form.reset();">
</form>
</body>
Have you tried replacing the submit button with a regular button, doing the validation in the onClick handler, and then submitting the form from within the onClick handler?
Edit: e.g. replace
<input onkeypress="return handleEnter(this, event)" type="submit" value="Submit" onclick="BG.startChatWithIssueForm(this.form, true); return false;" />
with
<input onkeypress="return handleEnter(this, event)" type="button" value="Submit" onclick="BG.handleSubmit(this.form, true);" />
Then maybe use a Javascript function like this (I'm not sure exactly what order you want these things to happen in):
BG.handleSubmit = function(formElement, fallBackToFullWindow) {
if (!formValidator())
return;
BG.startChatWithIssueForm(formElement, fallBackToFullWindow);
formElement.submit();
return false;
}
Edit: Your validation function should probably return false if it finds something invalid.
function formValidator(){
// Make quick references to our fields
var issueid = document.getElementById('issueid');
var username = document.getElementById('username');
var userid = document.getElementById('userid');
var issuedesc = document.getElementById('issuedesc');
var valid = true;
// Check each input in the order that it appears in the form
if(!madeSelection(issueid, "Please choose an issue"))
valid = false;
if(!notEmpty(username, "Please enter your name"))
valid = false;
if(!isAlphanumeric(username, "Numbers and Letters Only for name"))
valid = false;
if(!notEmpty(userid, "Please enter your user ID"))
valid = false;
if(!isAlphanumeric(userid, "Numbers and Letters Only for user ID"))
valid = false;
if(!notEmpty(issuedesc, "Please type a description of your problem"))
valid = false;
return valid;
}
I have a html input button like this
<input type="button" id="send_button" class="form_button" value="Send" onclick="return validateTextBoxes();" runat="server" />
And also I have javascript
<script language="javascript">
function validateTextBoxes()
{
var reading1 = document.getElementById('<%= meterReading1.ClientID%>').value;
var error = document.getElementById('<%= lblError.ClientID%>');
var btn = document.getElementById('<%= send_button.ClientID%>');
var ValidationExpression = /[\d]/;
if (reading1 == "" )
{
error.innerHTML = "Please enter Water Meter Reading.";
return false;
}
else if(!ValidationExpression.test(reading1)) {
error.innerHTML = "Please enter valid Meter Reading(It Contains only numbers)";
return false;
}
else
{
error.innerHTML = "";
return true;
}
}
</script>
And I am also calling this server click event in the code behind file
this.send_button.ServerClick += new System.EventHandler(this.send_ok);
So here is the problem when javscript returns true its not firing the serverclick event.
Please help me where I am doing wrong(I am using framework 1.1)
Thanks
I had this problem once and I actually had to do something like this:
onclick="if (validateTextBoxes()) { return true; } else { return false; }"
You absolutely should not have to do this and it made no sense to me why it would be have this way, but alas, I tried it and it worked :(