Find an element by id within a dynamically added control - javascript

I have an asp page in which I add dynamically a control I created (several times). In that control I have textbox for password and username and a revert button.
I use this javascript code in that control and it fails:
function HandlePasswordChanged() {
document.getElementById("<%=btnRevert.ClientID %>").disabled = false;
}
function HandleUserChanged() {
document.getElementById("<%=btnRevert.ClientID %>").disabled = false;
document.getElementById("<%=txtPassword.ClientID %>").disabled = false;
}
function btnRevertClick() {
document.getElementById("<%=btnRevert.ClientID %>").disabled = true;
document.getElementById("<%=txtPassword.ClientID %>").disabled = true;
document.getElementById("<%=txtUsername.ClientID %>").value = document.getElementById("<%=systemAccount.ClientID %>").value;
document.getElementById("<%=txtPassword.ClientID %>").value = "";
}
what it does is when I press the revert button on one control it disables the textbox on the other control - getelement fails to find the correct one.
How can I fix this?

If you are working on .net 4.0:
You can set ClientIDMode="Static" for your dynamically added controls. Also, you have to make sure you set unique ids for your controls.

I managed to find the solution.
The problem was that every time I added the acsx control with the javascript code it added multiple functions with the same name but the inside was different. when one control wanted to call its "own" function it just used the first one since they were all named the same.
My solution was to change the function from this:
function HandleUserChanged() {
document.getElementById("<%=btnRevert.ClientID %>").disabled = false;
document.getElementById("<%=txtPassword.ClientID %>").disabled = false;
}
to this:
function HandleUserChanged(btnRevertId, txtPasswordId, cellPasswordId) {
document.getElementById(btnRevertId).disabled = false;
document.getElementById(txtPasswordId).disabled = false;
}
and then in the c# code I add this:
txtUsername.Attributes.Add("onchange", "HandleUserChanged(\"" + btnRevert.ClientID + "\", \"" + txtPassword.ClientID + "\", \"" + cellPassword.ClientID + "\")");
This way each control know exactly which controls belong to him and sends the correct parameters to the function.

Related

javascript validating the whole form

Friends i am new to javascript, I am trying to write a script to validate the entire form whenever any input field value is changed of input fiels with the data attribute of required.
HTML
<form>
<input type="text" name="FirstName" class="inputField" data-required="true"></input>
<input type="text" name="MiddleName" class="inputField"></input>
<input type="text" name="LastName" class="inputField" data-required="true"></input>
</form>
SCRIPT
var field, required, isValid, fieldVal;
function validatedForm() {
field = document.querySelectorAll('.inputField');
document.getElementById("submitButton").disabled = true;
var isValid = true;
for(var i=0; i < field.length; i++){
required = field[i].dataset.required;
if(required){
field[i].addEventListener('blur', function(e){
fieldVal = this.value;
if(fieldVal == ''){
isValid = false;
}
checkSubmitBtn();
}, true);
}
}
function checkSubmitBtn() {
if(isValid = true) {
console.log(isValid);
document.getElementById("submitButton").disabled = false;
}
}
}
window.addEventListener("load", validatedForm);
PROBLEM 1:
The isValid is not updating hence even an empty blur on the input field makes the button disable to be false.
PROBLEM 2:
In case there are multiple forms on the page then how to validate only the desired forms .. just like in jQuery we add a script tag in the end to initialize the script according to it.
PROBLEM 3:
Is there a way to change the disable state of the button without the GetElementID ... I mean if that can be managed depending on the submit button of that particular form on the page where the script is suppose to work.
Any help will be highly appreciated. Thanks in advance.
I think you need something like the following form validation..
<script type="text/javascript">
var field, fieldVal, required = false;
function validatedForm() {
field = document.querySelectorAll('.inputField');
document.getElementById("submitButton").disabled = true;
field.forEach(function(elem) {
required = elem.dataset.required;
if(required){
elem.addEventListener('blur', function(e) {
checkSubmitBtn(field);
});
}
});
}
function checkSubmitBtn(field) {
var isDisabled = false;
field.forEach(function(elem) {
fieldVal = elem.value.trim();
if(fieldVal == ''){
isDisabled = true;
return false;
}
});
document.getElementById("submitButton").disabled = isDisabled;
}
window.addEventListener("load", validatedForm);
</script>
I hope it helps...
There are quite a few things going on here. First, your checkSubmitBtn function used a single = operator in the if statement. This won't actually check the variable, it instead will set the variable to that value. Here is the fixed function:
function checkSubmitBtn() {
if (isValid == true) {
document.getElementById("submitButton").disabled = false;
}
}
You mentioned not wanting to use getElementById. There are a few ways around this. One way would be to call the function once and store it in a variable to use later, like so:
var button = document.getElementById("submitButton");
...
function checkSubmitBtn() {
button.disabled = !isValid;
}
Another way would be to use jQuery. It still is technically calling getElementById in the backend, but the code is much simpler. If you wanted to avoid that, you also can still combine this with the technique I described above.
$("#submitButton").attr("disabled", !isValid);
I'd also like to point out that your code doesn't account for a situation where a form goes from invalid (starting point) to valid and back to invalid again. Say a user types in all of the fields but then backspaces everything. Your code will fall apart.
Lastly, your <input> HTML tags should not be closed. There are certain tags that are considered "self-closing", i.e. you don't have to write the closing tag, </input>.

how to use onclick in addeventlistener to prevent form data to be submitted?

This is just some part of my code .the thing which I am not understanding is how to use onclick in my html to prevent my php file from running. I have html file where my input is button type and I am using DOM2 that is .addeventlistener
function checku(event) {
var start=event.currentTarget;
var warning="";
if(start.name=="pressed"){
alert("sdf");
var temp=document.getElementById("form");
}
else
var temp=start;
var size=temp.length;
for(var i=0;i<size;i++) {
//alert(temp[i].name);
if(temp[i].name=="Email"){
var re = /^[0-9a-zA-Z]+#+[a-zA-Z]+?\.[a-z]{2,3}$/;
var len=temp[i].value.length;
var t=re.test(temp[i].value)
if(t==true||len==0){
document.getElementById("user").innerHTML="";
// Email.style.color="black";
if(len==0){
warning+="Email Address cannot be empty, ";
//return false;
}
//return true;
} else {
user.style.fontStretch="condensed";
user.style.color="red";
user.style.fontWeight="600";
user.style.fontFamily="Arial, Helvetica, sans-serif";
// Email.style.color="red";
document.getElementById("user").innerHTML="It should contain # and .com or.ca ";
warning+="Email Address, ";
//return false;
}
}
Try this code.
var div = document.getElementById('myDiv');
div.addEventListener('click', function(e){
e.preventDefault();
// Your code here
});
The button inside your form tag, when clicked, will trigger the submit event and submit the form to the URL specified in the action attribute of the form.
If you are adding an event to carry out validation or other stuff, make sure that you change your button's type attribute to button i.e. <button type='button'>Submit</button>

Using Blur and Submit events on the same form

I am still confused about this. Started learning JQuery about a week now and this is what I have:
var IsValidUserName = false;
$(document).ready(function () {
$('#txtUserName').blur(function () {
if ($('#txtUserName').val().match(isNumberLetter) &&
($('#txtUserName').val().length >= 8)) {
$('#userNameError').removeClass("error").addClass("default");
$('#txtUserName').removeClass("alert");
$('#txtUserName + label').removeAttr("id", "lblUserName");
IsValidUserName = true;
}
else {
$('#userNameError').removeClass("default").addClass("error");
$('#txtUserName').addClass("alert");
$('#txtUserName + label').attr("id", "lblUserName");
}
});
});
Lets say I have another function like above, lets say FirstName:
How do I call this on the submit event? The code works as I need it to when the user leaves a field. Not sure how I can also call this code and also use the variable above to prevent submit if the data entered is invalid.
I need to call the validation above if the user clicks the submit button and stop the submission if the IsValidUserName variable is false.
Somethings just need a little push.
Thanks my friends.
Guy
You could always extract it into a function instead of an anonymous function and pass the reference to the object you want to check. This would give you the added benefit of reusing it for other elements.
function validate(ele) {
var valid;
if (ele.val().match(isNumberLetter)) && (ele.val().length >= 8)) {
valid = true;
// update user here.
} else {
valid = false;
// update user here.
}
return valid;
}
$(function(){
$('#firstName').blur(function(){ validate($(this)); });
$('#lastName').blur(function(){ validate($(this)); });
$("yourFrom").submit(function(){
var firstNameIsValid = validate($('#firstName'));
var lastNameIsValid = validate($('#lastName'));
if (!nameIsValid) && (!lastNameIsValid) {
return false;
// User has already been updated
}
});
});
Also, since you are already heavily using javascript for your validation (hope this is convenience and not the only security), you can also disable the submit button entirely until the form meets the proper requirements.

How to handle alert in UI Automation using javascript?

In my application after tapping on a one button it gives and alert.There are two button on alert window: 1. Cancel 2. Ok
I have tried to tap on OK by using the solution given on the forum but it dosen't work.
UIATarget.onAlert = function onAlert(alert) {
var title = alert.name();
UIALogger.logWarning("Alert with title '" + title + "' encountered!");
if (title == "Attention")
{
alert.buttons()["OK"].tap();
return true; // bypass default handler
}
return false; // use default handler
}
Function for handling alert dosen't called.Can anyone help me on this issue?
Thanks in advance.
UIATarget.onAlert = function onAlert(alert)
{
UIATarget.localTarget().delay(1);
UIALogger.logMessage("alertShown");
target.captureScreenWithName("AlertCaptured");
return true;
}
app.alert().buttons()["OK"].tap();
My solution to this problem was to add an one second delay after the function that handles the alert. You can not end your script with that function.
UIATarget.onAlert = function onAlert(alert) {
var title = alert.name();
UIALogger.logWarning("Alert with title '" + title + "' encountered.");
if (title == "Are you sure you want to delete this?") {
alert.buttons()["Delete"].tap();
return true; //alert handled, so bypass the default handler
}
return false;
}
target.delay(1);

Get the id of element focus is moving to in jQuery.blur event?

I've written some code using jQuery to do an ajax call and display a message on the page when the user moves focus away from a field. My field is called txtLogin and the user types in some text and clicks a button to create a new user account in a database using the given txtLogin value.
The issue is that a valid value must contain four letters, a dash, and then four more letters. My client insists that the form should have two fields, one for the first four letters, and another for the second four letters.
Suppose that these two fields are called txtLogin0 and txtLogin1. I still want to do an ajax call when the user moves focus away from the field, but the ajax call should not be invoked when the user moves from one of the two fields to the other!
My current code looks like this.
$('#txtLogin').blur(function() {
var login = $(this).val();
var isValid = testLogin(login);
if (!isValid) alert('Login is invalid');
});
I imagine my new code looking like this:
$('#txtLogin0').add('#txtLogin1').blur(function() {
var focusId = The Id of the newly focused element
if (focusId==='txtLogin0' || focusId==='txtLogin1) return
var login = $(#txtLogin0').val() + '-' + $('#txtLogin1').val();
var isValid = testLogin(login);
if (!isValid) alert('Login is invalid');
});
How can I get the id of the element that the focus moves to in the jQuery.blur event?
A simple hack is to create two var to store the current and previous element in onfocus and onblur and call the validate method inside a timer which will be triggered in 0 milli seconds.. Try below code and I think it is close to what you want.
DEMO
var prevEl, curEl;
$(document).ready(function() {
$('#txtLogin0, #txtLogin1').blur(function() {
prevEl = this.id;
setTimeout(validateLogin, 0);
}).focus(function() {
curEl = this.id;
});
});
function validateLogin() {
if ((prevEl === 'txtLogin0' && curEl === 'txtLogin1') || (curEl === 'txtLogin0' && prevEl === 'txtLogin1')) {
return;
}
prevEl = ''; curEl = '';
var login = $('#txtLogin0').val() + '-' + $('#txtLogin1').val();
var isValid = testLogin(login);
if (!isValid) alert('Login is invalid');
}
function testLogin(txt) {
return false;
}
var focusId = $(this).attr('id');

Categories