asp.net/javascript, why is textbox onChange event does not fire? - javascript

I want it to happen when after user select the userID then the userID show up on first readonly textbox then the onChange event should fire when it show on first readonly textbox so it can copy this userID to second textbox. However it doesn't work, it only worked is the userID show up on first textbox but the onChange doesn't trigger for second texbox.
Here half working codes:
<tr>
<td align="right">
Secondary Owner
</td>
<td>
<input id="Hidden1" type="hidden" />
<asp:TextBox ID="tbAdd_Sowner" runat="server" Enabled="false"></asp:TextBox>
<input id="Hidden2" type="hidden" />
<input id="Hidden3" type="hidden" />
<a href="javascript:void(0)" onclick="GalModalTOCCDialog(Hidden1, tbAdd_Sowner, Hidden2,Hidden3)">
Get User ID</a>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" ValidationGroup="g1" runat="server" ErrorMessage="* Required" ControlToValidate="tbAdd_Sowner"> <b style="color:Red;"> * </b></asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender8" runat="server" TargetControlID="RequiredFieldValidator7">
</asp:ValidatorCalloutExtender>
</td>
</tr>
<tr>
<td align="right">Secondary Owners</td>
<td>
<asp:TextBox ID="tbAdd_Sphone" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator13" ValidationGroup="g1" runat="server" ErrorMessage="* Required" ControlToValidate="tbAdd_Sphone"> <b style="color:Red;"> * </b></asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender9" runat="server" TargetControlID="RequiredFieldValidator13">
</asp:ValidatorCalloutExtender>
</td>
</tr>
Then a javascript codes in <head> to copy first textbox value and put to second textbox:
<script>
function getUserID() {
document.getElementById('tbAdd_Sphone').value = document.getElementById('tbAdd_Sowner').value;
}
document.getElementById('tbAdd_Sowner').onchange = getUserID();
</script>
Edited: I add a GALModalDialog.js codes here because some of you want to see what it like. I also have GALToCCDialong.asp that listed userid to choose and XMLGALListbox.asp that get the userid from ADs.
function PopulateListboxFromString(oListbox,vNames,vUserIDs){
var oArrayUserNames = vNames.value.split(';');
var oArrayUserIDs = vUserIDs.value.split(';');
for (var index=0;index < oArrayUserIDs.length;index++) {
if (oArrayUserNames[index] != ''){
var oOption = document.createElement("OPTION");
oListbox.options.add(oOption);
oOption.innerText = oArrayUserNames[index];
oOption.value = oArrayUserIDs[index];
}
}
};
function GalModalTOCCDialog(oTONames, oTOUserIDs,oCCNames, oCCUserIDs ) {
if (oCCNames != null){
var oInputArray = new Array(oTONames.value,oTOUserIDs.value,oCCNames.value,oCCUserIDs.value);
} else {
var oInputArray = new Array(oTONames.value,oTOUserIDs.value,'','');
}
var oOutputArray = window.showModalDialog('GalAccess/GALToCCDialog.asp', oInputArray, 'dialogWidth:510px;dialogHeight:400px;status:no;help:no;');
// Check if we get something back;
// User might have closed the window without using the buttons
if (oOutputArray != null){
//first element is true if user clicked OK
if (oOutputArray[0]) {
if (oCCNames != null){
oTONames.value = oOutputArray[1];
oTOUserIDs.value = oOutputArray[2];
oCCNames.value = oOutputArray[3];
oCCUserIDs.value = oOutputArray[4];
} else {
oTONames.value = oOutputArray[1];
oTOUserIDs.value = oOutputArray[2];
}
}
}
return false;
}
function GalModalDialog(oSelectObject, oUserID) {
if (oUserID == null){
// there is a select object to fill data from
// fill the input array
var oInputArray = new Array(new Array(oSelectObject.options.length),new Array(oSelectObject.options.length));
for (var index=0;index < oInputArray[0].length;index++) {
oInputArray[0][index] = oSelectObject.options[index].innerText;
oInputArray[1][index] = oSelectObject.options[index].value;
};
var oOutputArray = window.showModalDialog('../GALDialog/GALModalDialog.asp', oInputArray, 'dialogWidth:500px;dialogHeight:320px;status:no;help:no;');
// Check if we get something back;
// User might have closed the window without using the buttons
if (oOutputArray != null){
//first element is true if user clicked OK
if (oOutputArray[0]) {
//remove existing from end to beginning otherwise not all options are removed.
var length=oSelectObject.options.length;
for (var index=length-1;index >= 0;index--) {
oSelectObject.options[index] = null;
};
// copy the array
for (var index=0;index < oOutputArray[1].length;index++) {
var oOption = document.createElement("OPTION");
oSelectObject.options.add(oOption);
oOption.innerText = oOutputArray[1][index];
oOption.value = oOutputArray[2][index];
};
}
}
} else
{
// there are 2 text objects to fill data from; the first contains the name, the secound the userid.
//if (oSelectObject.value != '' ) {
// var oInputArray = new Array(new Array(1),new Array(1));
//
// oInputArray[0][0] = oSelectObject.value;
// oInputArray[1][0] = oUserID.value;
//} else {
var oInputArray = new Array(new Array(0),new Array(0));
//}
var oOutputArray = window.showModalDialog('../GALDialog/GALModalDialog.asp', oInputArray, 'dialogWidth:500px;dialogHeight:320px;status:no;help:no;');
if (oOutputArray != null){
//first element is true if user clicked OK
if (oOutputArray[0]) {
// copy the data
oSelectObject.value = oOutputArray[1][0];
oUserID.value = oOutputArray[2][0];
}
}
}
return false;
}
Edited: Here is codes of GALToCCDialog.asp. In SubmitOnclick function and else if(vAction == 'OK') is where I click OK button from selected userid to submit to textbox.
<SCRIPT ID=clientEventHandlersJS LANGUAGE=javascript>
<!--
function List_onkeydown(oList) {
if( event.keyCode == 46 ){
if ((oList.selectedIndex != -1)&&(oList.options[oList.selectedIndex].value != '')){
oList.options[oList.selectedIndex] = null;
}
}
}
//-->
</SCRIPT>
<script language="jscript">
function InitializeListbox(idXML, idSpan){
// get to the XML specifying the names
var oSelects;
var strXML;
oSelects = idXML.XMLDocument.documentElement.childNodes;
strXML = '';
// Get all the options in 1 string
for (var index=0;index< oSelects.length;index++){
strXML = strXML + oSelects[index].xml;
}
// the error handlingis there if idSpan refers to multiple objects
// Insert the options in the html before the end of the SELECT
// window.alert(strXML);
//idSpan.innerHTML = replace(idSpan.innerHTML,"</SELECT>",strXML & "</SELECT>");
idSpan.innerHTML = '<SELECT id=idUserSelect size=12 style="width:190px">' + strXML + '</SELECT>';
}
function SubmitOnclick(vAction, oObject){
//DistList.action = "DistList.asp?Action=" & vAction ;
if (vAction == 'Add'){
if ((idUserSelect.value!='')&&(idUserSelect.value!='Unknown')){
var oOption = document.createElement("OPTION");
oObject.options.add(oOption);
oOption.innerText = idUserSelect.options[idUserSelect.selectedIndex].text;
oOption.value = idUserSelect.options[idUserSelect.selectedIndex].value;
}
} else if(vAction == 'Find') {
idXMLUsers.src ='XMLGALListbox.asp?Searchstring=' + SearchString.value;
} else if(vAction == 'Remove'){
if ((idMyList.selectedIndex != -1)&&(idMyList.options[idMyList.selectedIndex].value != '')){
idMyList.options[idMyList.selectedIndex] = null;
}
} else if(vAction == 'OK'){
//window.returnValue = cal.day + ' ' + MonthNames[cal.month-1] + ' ' + cal.year ;
// create an array
var TONames = ''
var TOUserIDs = ''
var CCNames = ''
var CCUserIDs = ''
for (var index = 0; index < 1; index++) {
TONames = TONames + idTOList.options[index].innerText;
TOUserIDs = TOUserIDs + idTOList.options[index].value;
};
//Commented out by Nick, use if you want multiple userIDs etc...
//for (var index=0;index < idTOList.options.length;index++) {
// TONames = TONames + idTOList.options[index].innerText ;
// TOUserIDs = TOUserIDs + idTOList.options[index].value ;
//};
//for (var index=0;index < idCCList.options.length;index++) {
//CCNames = CCNames + idCCList.options[index].innerText ;
//CCUserIDs = CCUserIDs + idCCList.options[index].value ;
//};
var oArray = new Array(true,TONames,TOUserIDs,CCNames,CCUserIDs);
window.returnValue = oArray;
//window.alert(TONames);
//window.alert(TOUserIDs);
//window.alert(CCNames);
//window.alert(CCUserIDs);
window.close();
} else if(vAction == 'Cancel'){
var oArray = new Array(false);
window.returnValue = oArray;
window.close();
}
}
function OnBodyLoad() {
//window.alert('test');
//clear all list data
try{
var oArray = window.dialogArguments;
//PopulateListboxFromString(idTOList,oArray[0],oArray[1])
//PopulateListboxFromString(idCCList,oArray[2],oArray[3])
} catch(e)
{
}
};
function PopulateListboxFromString(oListbox,vNames,vUserIDs){
var oArrayUserNames = vNames.split(';');
var oArrayUserIDs = vUserIDs.split(';');
for (var index=0;index < oArrayUserIDs.length;index++) {
if (oArrayUserNames[index] != ''){
var oOption = document.createElement("OPTION");
oListbox.options.add(oOption);
oOption.innerText = oArrayUserNames[index];
oOption.value = oArrayUserIDs[index];
}
}
};
function OnBodyLoad__() {
//window.alert('test');
try{
var oArray = window.dialogArguments;
for (var index=0;index < oArray[0].length;index++) {
var oOption = document.createElement("OPTION");
idMyList.options.add(oOption);
oOption.innerText = oArray[0][index];
oOption.value = oArray[1][index];
};
} catch(e)
{
};
};
</script>
<body class="cellcolorlightest content" onload="OnBodyLoad();">
<xml id="idXMLUsers" src="XMLGALListbox.asp?Searchstring=" ondatasetcomplete="InitializeListbox(idXMLUsers, idUsers);"></xml>
<table class="TableBorderNormal" width="100%" border=0 cellspacing="1" cellpadding="1">
<colgroup>
<col width="50%"></col><col></col><col width="50%"></col>
<thead>
<tr>
<td colspan="3" class="TDvwvInfo" align="left"><STRONG>Find Name</STRONG><br><FONT size=2>Type name and hit "Search"</FONT></td>
</tr>
<tr>
<td class="TDvwvInfo" align="left"><input name="SearchString" style="WIDTH: 190px" size="20"> </td>
<td class="TDvwvInfo" align="middle" valign=top><input type="button" value="Search" name="Find" onclick="SubmitOnclick('Find')"></td>
<td class="TDvwvInfo" align="left"></td>
</tr>
<tr>
<td class="TDvwvInfo" align="left" nowrap><STRONG>Users found</STRONG><br><FONT size=2>Select from list and hit "Select" to add</FONT></td>
<td class="TDvwvInfo" align="middle"></td>
<td class="TDvwvInfo" align="left" valign=top><STRONG>Get User ID</STRONG><br></td>
</tr>
</thead>
<tr>
<td class="TDvwv" align="left" width="33%" rowspan=2 valign=top><span id="idUsers"> </span> </td>
<td class="TDvwvInfo" align="middle" valign=top width="33%">
<input type="button" value="Select >" name="Add" onclick="SubmitOnclick('Add', idTOList);"><br><br>
</td>
<td class="TDvwv" align="left" width="33%" valign=top>
<select id="idTOList" size="5" style="WIDTH: 190px" LANGUAGE=javascript onkeydown="return List_onkeydown(this)"> </select><br>
<br />
<b style="color:red">* Only add one user, if you added the wrong user click cancel and try again.</b>
</td>
</tr>
<tr>
<td align=middle valign=top>
<!-- <input type="hidden" value="CC >" name="CC" onclick="SubmitOnclick('Add', idCCList);" disabled="disabled"><br><br> --> <!--INPUT name=Remove onclick="SubmitOnclick('Remove');" type=button value=" < Remove"--></td>
<td align=left valign=top>
<!--<select id=idCCList size=5 style="WIDTH: 190px" LANGUAGE=javascript onkeydown="return List_onkeydown(this)" disabled="disabled" visible="false"></select></td>-->
</tr>
<tr>
<td align="middle" ></td>
<td align=middle></td>
<td align=left>
<input type="button" value="OK" name="OK" onclick="SubmitOnclick('OK',null);">
<input type="button" value="Cancel" name="Cancel" onclick="SubmitOnclick('Cancel',null);"></td>
</tr>
</table>
</body>
</html>

Use
document.getElementById('<%= tbAdd_Sphone.ClientID %>')
instead of
document.getElementById('tbAdd_Sphone')
MSDN Control.ClientID Property

Changing the value of tbAdd_Sowner through JavaScript (I assume through your GalModalTOCCDialog function) isn't going to fire the onchange event.
You can fire that event manually, after you set the value:
document.getElementById('tbAdd_Sowner').onchange();
Though I'm surprised you aren't have problems with getElementById like #IrfanTahirKheli showed, which should've worked fine for you... so there are likely missing pieces of your markup that we need to help you correctly.
Other things you need to strongly consider is to not use inline styling and not use tables for formatting.
Since you seem to have problems with what I added, here is another way. Remove the onChange from your asp:TextBox and just do it all from javascript:
document.getElementById('tbAdd_Sowner').value = 'somevalue';
document.getElementById('tbAdd_Sowner').onchange = getUserID();

You cannot make change event just by setting value from javascript. Here is a sample by using trigger.
<script>
$(document).ready(function () {
$(".tbAdd_Sowner").on('change', function () {
var owner = $('.tbAdd_Sowner').val();
$('.tbAdd_Sphone').val(owner);
});
$(".aGetID").on('click', function () {
var tbOwner = $('.tbAdd_Sowner');
var hidden1 = $('.Hidden1');
var hidden2 = $('.Hidden2');
var hidden3 = $('.Hidden3');
GalModalTOCCDialog(hidden1, tbOwner, hidden2, hidden3);
});
function GalModalTOCCDialog(Hidden1, tbAdd_Sowner, Hidden2, Hidden3) {
$(tbAdd_Sowner).val(' ').trigger('change');
}
$('.tbAdd_Sowner').change(function () {
$(this).removeAttr('disabled');
});
});
</script>
Here is your code, removing those validators
<table>
<tr>
<td align="right">Secondary Owner
</td>
<td>
<input id="Hidden1" type="hidden" value="1" class="Hidden1" />
<asp:TextBox ID="tbAdd_Sowner" OnTextChanged="tbAdd_Sowner_TextChanged" CssClass="tbAdd_Sowner" AutoPostBack="true" runat="server" Enabled="false" ></asp:TextBox>
<input id="Hidden2" type="hidden" class="Hidden2" />
<input id="Hidden3" type="hidden" class="Hidden3" />
<a href="javascript:void(0)" id="aGetID" class="aGetID" >Get User ID</a>
</td>
</tr>
<tr>
<td align="right">Secondary Owners</td>
<td>
<asp:TextBox ID="tbAdd_Sphone" runat="server" CssClass="tbAdd_Sphone" ></asp:TextBox>
</td>
</tr>
</table>
Server side.
protected void tbAdd_Sowner_TextChanged(object sender, EventArgs e)
{
tbAdd_Sowner.Text = "123";
}

use this <asp:TextBox ID="TextBox1" runat="server"
onkeypress="document.getElementById('id').Value=this.value;" />

Like others have mentioned in their answers,
<asp:TextBox id="tbAdd_Sphone" runat="server" />
will have a server-side dynamic client-ID prefixed to the generated HTML. If you see the source code of the page (or use the developer tools) in a browser of choice, you will notice you the ID is different than what you are passing in to your method call i.e something like this:
<textarea id="ctl00_OuterASPControlID_tbADD_Sphone"></textarea>
You can keep the className static by using class="tbAdd_Sphone" if the class is dynamically prefixed too. Or, try to get element by ID on
<%=tbAdd_Sphone.ClientID %>
You can either set the ClientID mode to static, or you can try using UniqueID.
Another thing to note, javascript has a special behavior. If you call of a method with a set number of variables passed in correctly in the call, it will only use those values in the functionality. If there is null/undefined data passed into the call, the rest of the parameters are just ignored.
functionName:function(parameter1, parameter2) {
//Default behavior can be overridden if parameter2 is not passed in as expected.
if(parameter2 ==null || parameter2=='undefined') {
parameter2 = "Some value";
}
}
functionName("testPar1"); //Works but parameter2 is not passed in as expected
functionName("testPar1", "testPar2"); //Works
functionName("testPar1", undefined); //Works, but parameter2 is not passed in as expected
If you need to use the id for phone, either do a substring search for getting the element by the actual ID, or use a getElementsByTag in your javascript to search for textboxes, and you can use any other property, say in plain Javascript:
var x = document.getElementsByTag("textbox");
if(x!=null && x.attribute('class') == 'tbAdd_Sphone' ) {
var valueX = x.attribute('value');
}

Related

Javascript returning correct & undefined value

Sorry the title is vague, but I have a form that accepts multiple id and posts the users input to URL to open x amount of tabs depending on the number of account id's.
The link for the first account id is opening with the values inserted into the form but the second account id is just showing "undefined" and from console looks like the second account id isn't getting past the first declaration but skipping to the second.
<form accept-charset="UTF-8" method="post"><div style="margin:0;padding:0;display:inline">
<table class="vat-tax-processor center-table">
<tbody>
<tr>
<td>
<span class="required">*</span>
AWS Account ID (No Dashes)<br>
</td>
<td><textarea autocomplete="off" id="AccountIDs" name="AccountIDs" value=""></textarea></td>
<tr>
<td>
<span class="required">*</span>
VAT Country <br>
</td>
<td><input autocomplete="off" type="text" value="" id="vatCountryCode" name="vatCountryCode"></td>
</tr>
<tr>
<td>
<span class="required">*</span>
Vat Number<br>
</td>
<td><input autocomplete="off" type="text" value="" id="vatNumber" name="vatNumber"></td>
</tr>
<tr>
<td>
<span class="required">*</span>
Registration Type <br>
</td>
<td><input autocomplete="off" type="text" value="Intra-EU" id="currentState" name="currentState"></td>
</tr>
<tr>
<td>
<span class="required">*</span>
Business Legal Name <br>
</td>
<td><input autocomplete="off" type="text" value="" id="businessLegalName" name="businessLegalName"></td>
</tr>
<tr>
<td>
Here is my js:
function addExemption(){
var AccountIDsArray = $('textarea[id=AccountIDs]').val().split('\n');
var vatCountryCodeArray = $('input[id=vatCountryCode]').val().split('\n');
var vatNumberArray = $('input[id=vatNumber]').val().split('\n');
/*var currentStateArray = $('input[id=currentState]').val().split('\n');*/
var businessLegalNameArray = $('input[id=businessLegalName]').val().split('\n');
console.log('I got past part 1 declarations - No issues here');
$.each(AccountIDsArray, function(index, value){
var AccountID = AccountIDsArray[index];
var vatCountryCode = vatCountryCodeArray[index];
var vatNumber = vatNumberArray[index];
/*var currentState = currentStateArray[index];*/
var businessLegalName = businessLegalNameArray[index];
console.log('I got part part 2 declarations - No issues here either');
console.log(AccountID);
var URL = 'https://linkhere';
var URL_Final = encodeURI(URL);
window.open(URL_Final, '_blank');
}
);
Here is a screenshot of what appears on first link and second link:
Account 1
Account 2
There are a couple issues I see with this.
The window is opening in your loop meaning that it will open a window immediately after the first id is printed to the console. I would move window.open() outside of the $.each.
You are risking out of bounds indexing on vatCountryCodeArray, vatNumberArray, currentStateArray and businessLegalNameArray since they are input elements and not textareas.
The 'Undefined' you see if because your function has no return value. See here.
function addExemption(){
var AccountIDsArray = $('textarea[id=AccountIDs]').val().split('\n');
var vatCountryCodeArray = $('textarea[id=vatCountryCode]').val().split('\n');
var vatNumberArray = $('textarea[id=vatNumber]').val().split('\n');
var currentStateArray = $('textarea[id=currentState]').val().split('\n');
var businessLegalNameArray = $('textarea[id=businessLegalName]').val().split('\n');
console.log('I got past part 1 declarations - No issues here');
$.each(AccountIDsArray, function(index, value){
if(value != null && value != ''){
var AccountID = value;
//var vatCountryCode = vatCountryCodeArray[index];
//var vatNumber = vatNumberArray[index];
//var currentState = currentStateArray[index];
//var businessLegalName = businessLegalNameArray[index];
console.log('I got part part 2 declarations - No issues here either');
console.log(AccountID);
}
});
var URL = 'https://linkhere';
var URL_Final = encodeURI(URL);
window.open(URL_Final,'_blank');
return '';
}
I was able to resolve this like so:
function addExemption(){
var AccountIDsArray = $('textarea[id=AccountIDs]').val().split('\n');
console.log('I got past 1st declarations - No issues here');
$.each(AccountIDsArray, function(index, value){
var AccountID = AccountIDsArray[index];
var vatCountryCode = $('#vatCountryCode').val();
var vatNumber = $('#vatNumber').val();
var businessLegalName = $('#businessLegalName').val();
console.log('I got past 2nd declarations - No issues here either');
console.log(AccountID);
var URL = 'https:xxxxx?accountId=' + AccountID + '&vatCountryCode=' + vatCountryCode + '&vatNumber=' + vatNumber + '&currentState=Intra-EU&businessLegalName=' + businessLegalName + '';
var URL_Final = encodeURI(URL);
window.open(URL_Final, '_blank');
});
}

Why this form is submitted also if this script forbids the submission?

I am absolutely new in JavaScript development and I have the following problem.
I have a form containing two input tags where the user can insert two dates (something like dateFrom and dateTo) using a calendar script visualization and a submit button (named Cerca).
When the user click the submit button it is performed a JavaScript that check if the two dates are correct (if both the dates are set and if the dateTo is later the dateFrom). If the two dates are correct the form is submitted to a Java Servlet, otherwise it is not submitted.
So this is my form (dataDa means dateFrom and dataA means dateTo):
<form id="dataDaAForm" name="dataDaAForm" action="salwf.do?serv=<%=request.getSession(false).getAttribute("service")%>&matricola=<%=request.getSession(false).getAttribute("matricola")%>" method="post">
<div class="customPanel" style="width: 100% !important; overflow-y: auto;">
<div class="pane">
<table class="dataDaATable" width="100%">
<tr>
<!-- DATA DA: -->
<td align="right">
Da:
</td>
<td>
<input type="hidden" size="9" class="impPrfTot" readonly="readonly"
onchange="cambioDataDa(this.value)"
name="dataDa" id="datada" value=""
style="font-size: 11px;color: #000000;">
<input id="datada2" onchange="" type="text" maxlength="9" size="9"
class="impPrfTot"
readonly="readonly" style="width: 100px" value="<%=request.getSession(false).getAttribute("dataDa")%>"
style="font-size: 11px;color: #000000;">
<img style="cursor:pointer;margin-left: 3px;"
src="js/calendar/cal.gif"
alt="Seleziona data" border="0"
onClick="displayCalendar(document.getElementById('datada'),'yyyymmdd',this)">
</td>
<!-- DATA A: -->
<td align="right">
A:
</td>
<td>
<input type="hidden" size="9" class="impPrfTot" readonly="readonly"
onchange="cambioDataA(this.value)"
name="dataA" id="dataa" value=""
style="font-size: 11px;color: #000000;">
<input id="dataa2" onchange="" type="text" maxlength="9" size="9"
class="impPrfTot" value="<%=request.getSession(false).getAttribute("dataA")%>"
readonly="readonly" style="width: 100px"
style="font-size: 11px;color: #000000;">
<img style="cursor:pointer;margin-left: 3px;"
src="js/calendar/cal.gif"
alt="Seleziona data" border="0"
onClick="displayCalendar(document.getElementById('dataa'),'yyyymmdd',this)">
</td>
<!-- SUBMIT BUTTON: -->
<td>
<button class="dataDadataAButton" name="submitdataDadataA" onclick="testSubmit();">Cerca</button>
</td>
</tr>
</table>
</div>
</div>
</form>
And this is the script that check if the two dates are correct:
function testSubmit() {
//f = document.forms[0];
var f = document.getElementById('dataDaAForm');
//var dataConfermaDA = f.dataDa.value;
//var dataConfermaA = f.dataA.value;
var dataDa = f.dataDa.value;
var dataA = f.dataA.value;
// TODO:
if (!controllaDate(dataDa, dataA, "'Data Conferma'")) {
return false;
}
//f.action = "edimon.do?serv=M.5";
f.submit();
}
function controllaDate(DataDA, DataA, nomeCampo) {
var check_DataDA = (DataDA != "");
var check_DataA = (DataA != "");
var check_data_DA = check_DataDA;
var check_data_A = check_DataA;
if (!check_data_DA && (check_DataA)) {
alert(nomeCampo + " Selezionare correttamente Data Da");
return false;
}
if (!check_data_A && (check_DataDA)) {
alert(nomeCampo + " Selezionare correttamente Data A");
return false;
}
if (check_data_DA && check_data_A) {
/**
var giorno = DataDA.substr(6, 7);
var mese = DataDA.substr(4, 5);
var anno = DataDA.substr(0, 4);
var dataDa = new Date(anno, mese - 1, giorno);
var giorno = DataA.substr(6, 7);
var mese = DataA.substr(4, 5);
var anno = DataA.substr(0, 4);
*/
var giorno = DataDA.substring(6, 8);
var mese = DataDA.substring(4, 6);
var anno = DataDA.substring(0, 4);
var dataDa = new Date(anno, mese - 1, giorno);
var giorno = DataA.substring(6, 8);
var mese = DataA.substring(4, 6);
var anno = DataA.substring(0, 4);
var dataA = new Date(anno, mese - 1, giorno);
if (dataA < dataDa) {
alert(nomeCampo + " La Data Da deve essere minore o uguale alla Data A");
return false;
}
}
return true;
}
So, for example if I try to insert only the dataDa (dateFrom) value and not the dataA (dateTo) value what it happens is that when I click the Cerca button the testSubmit() JavaScript is performed.
Now in this script I have something like this:
dataDa = "20141202"
dataA = ""
(dataDa is set and dataA is empty)
So now it is called the controllaDate() script that perform the effective date checking.
So this script receives something like this (the received input parameters):
controllaDate("20141202", "", "'DataConferma'")
So executes this code snippet:
if (!check_data_A && (check_DataDA)) {
alert(nomeCampo + " Selezionare correttamente Data A");
return false;
}
and enter in this if (because check_data_A is false because dataA is not set).
So show the alert popup and return false to its caller that is the testSubmit() function.
So, as I expect, now come back to the testSubmit() in this point:
if (!controllaDate(dataDa, dataA, "'Data Conferma'")) {
return false;
}
and the testSubmit() function return false and should not submit my form because this operation is not performed:
f.submit()
But I don't know why the form is submitted anyway also if the f.submit() statement is not performed. Why? What am I missing?
Can I prevent in someway the form submitting when return false?
<button class="dataDadataAButton" name="submitdataDadataA" onclick="testSubmit();">Cerca</button>
You have a submit button. Clicking it will submit the form unless something prevents it.
The onclick function calls testSubmit (which returns false) but it does nothing with the return value from testSubmit. You have to return false from the onclick function to prevent the normal action of the submit button from happening.
onclick="return testSubmit();"
That said, onclick attributes are how we bound JavaScript to event handlers in the 90s. We have addEventListener now (and we can bind to the submit event of the form instead of assuming it will only be submitted by clicking a button).

Getting Value from html form with the same name attribute under Loop

I have a form which displays multiple rows from database with 4 columns. From these record I need to write a new value in 4th column and update database record. But whenever I try, only First Row value can be updated/read. But not the other rows!! This can be due to the same "name=redirection" as it is given to each from "for loop". So, how can I get the values from other rows too??
for (int i=0; i<domains.size(); i++) {
domainprops = (String[]) domains.get(i);
%>
<table cellspacing="0" cellpadding="10" border="0" class="tableview" width="100%">
<td width="150"><input type="text" id="domains" name="domains" value="<%=domainprops[0]%>"></td>
<td width="160"><input type="text" name="defaulturl" value="<%=domainprops[1]%>" size="30"></td>
<td width="160"><input type="text" name="redirecturl" value="<%=domainprops[2]%>" size="30"></td>
<td width="160"> <input type="text" id="redirection" name="redirection"></td>
<td align="right"><a href="javascript:win2('recordUpdate.jsp?domains=<%=domainprops[0]%>
')">[Update]</a></td>
</tr>
</table>
<% } %>
Javascript Code :
function win2(urlPath) {
var winl = (screen.width-200)/2;
var wint = (screen.height-100)/2;
var settings = 'height=100,width=200,directories=no,resizable=no,status=no,scrollbars=no,menubar=no,location=no,top=' + wint + ',left=' + winl;
var changeurls=document.getElementById("redirection").value;
urlPath+='&rdirect='+changeurls
editWin.focus();
}
An ID in the DOM is supposed to be unique. If any element in the DOM has an ID, it should not be shared by any other element.
What I would suggest doing is appending your loop counter on to the end of the ID. This will ensure that every element you create in the DOM has its own unique ID.
for (int i=0; i<domains.size(); i++) {
domainprops = (String[]) domains.get(i);
...
<input type="text" id="domains_<%= i %>" name="domains" value="<%=domainprops[0]%>">
...
<input type="text" id="redirection_<%= i %>" name="redirection"></td>
</tr>
</table>
}
Next, pass the loop counter to the win2 function call:
<td align="right"><a href="javascript:win2('recordUpdate.jsp?domains=<%=domainprops[0]%>
', <%= i %>)">[Update]</a></td>
Finally, adjust the function itself...
function win2(urlPath, loopID) {
...
var changeurls=document.getElementById("redirection_" + loopID).value;
urlPath+='&rdirect='+changeurls
...
}
EDIT: Please read the answer referring to having multiple elements with the same ID. You should not be using multiple of the same ID.
You could use Javascript to iterate over redirection form elements.
function loopThroughRedirection(form) {
var result = "";
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].name == 'redirection') {
// Do something to retrieve the value of redirection
result += form.elements[i].value
}
}
return result;
}

Inline form Validation

I'm trying to get my form to validate inline but can't seem to get the right syntax, at the moment I have this, which does nothing yet. The first function, formhandler is meant to change the span elements text if the element gets blured and take away the error text once the field is focused at the moment it does neither of these.
<html>
<script type = "text/javascript">
document.getElementById("form").onfocus = function formHandler() {
for(var i = 0; i < document.getElementById("form").length; i+=1){
if(document.getElementById("form").elements[i].type == 'text') {
if(document.getElementById("form").elements[i].focus()) {
var onode = document.getElementById("form").elements[i].nextSibling;
onode.innerHTML = "";
valid = true;
}
else if(document.getElementById("form").elements[i].blur()) {
var onode = document.getElementById("form").elements[i].nextSibling;
onode.innerHTML = "Please Fill in Field";
valid = false;
}
}
}
}
function validate() {
var valid = false;
for(var i = 0; i < document.getElementById("form").length; i+=1){
if(document.getElementById("form").elements[i].type == 'text') {
if(document.getElementById("form").elements[i].value == "") {
var onode = document.getElementById("form").elements[i].nextSibling;
onode.innerHTML = "Please Fill in Field";
valid = true;
}
else{
var onode = document.getElementById("form").elements[i].nextSibling;
onode.innerHTML = "";
valid = false;
}
}
}
}
document.getElementById("form").onsubmit = validate;
</script>
<head>
<title>Question 1 / Vraag 1 - Basic JavaScript Validaton / Basiese JavaScript validasie
</title>
<link rel="Stylesheet" type="text/css" href="style.css" />
</head>
<body>
<form method="get" action="" id = "form">
<table>
<tr>
<td> Firstname:</td>
<td> <input type="text" name="firstname" id="firstname" /><span id="fnError">
</span></td>
</tr>
<tr>
<td> Surname:</td>
<td> <input type="text" name="surname" id="surname" /><span id="snError">
</span></td>
</tr>
<tr>
<td> Age:</td>
<td> <input type="text" name="age" id="age" /><span id="aError">
</span></td>
</tr>
<tr>
<td> Email:</td>
<td><input type="text" name="email" id="email" /><span id="eError">
</span></td>
</tr>
<tr><td colspan="2"><input type="button" value="Validate" onclick = "validate()"/></td></tr>
</table>
</form>
</body>
</html>
I'm trying to achieve this without the use of jquery, so please don't suggest it, thanks in advance.
These are problems I found in your code:
Line 1: Forms don't have a .focus method. What did you mean for that to do?
Line 2: Change .length to .elements:
for (var i = 0; i < document.getElementById("form").elements.length; i++ ) {
var node = document.getElementById("form").elements[i];
...
The elements in the form are now aliased as node.
Lines 4: The .focus/.blur method doesn't return true if the element is out of focus. We're going to have to do it ourselves:
node.onfocus = function() { this.isInFocus = true; };
node.onblur = function() { this.isBlurred = !this.isInFocus; };
The resulting code is as follows:
if ( node.isInfocus ) { ... }
else if ( node.isBlurred ) { ... }
Line 9: Refer to above.
Wrap the code in a window.onload to be able to use the DOM elements when the DOM has loaded.
This is your revised code; let me know if it works for you:
var nodes = document.getElementById('form').elements, node;
for ( var i = 0; i < nodes.length; i++ ) (function(i) {
nodes[i].onfocus = function() { this.isInFocus = true; };
nodes[i].onblur = function() { this.isBlurred = !this.isInFocus; };
})(i);
for (var i = 0; i < nodes.length; i++) {
node = nodes[i];
if (node.type == 'text') {
if (node.isInFocus) {
var onode = node.nextSibling;
onode.innerHTML = "";
valid = true;
} else if (node.isBlurred) {
var onode = node.nextSibling;
onode.innerHTML = "Please Fill in Field";
valid = false;
}
}
}
First major problem: you are trying to do all of this in the initial script load. The main DOM is not yet loaded at that time so document.getElementById("form") won't find anything. Do the function definitions in an onload handler.
Also, not sure what you are expecting "valid" to bind to in the first function. Finally, once you have determined validity or not, you need to do something with the result.
You are referencing dom elements which don't exist yet. One solution would be to move all your <script> tag before </body>, so elements exist when the script is executed.
Another way, with pure javascript would be to do this:
<script>
window.onload = function(){
//All your code here
}
</script>
(The validate function could be outside if you want)
Cheers

I Want Pop Up Window To Appear If No Validation Errors

I have a button known as "Prepare Questions". Now when I click on this button, this button does two things, using the validaton() function it validates the form so that if there is an error in the form (empty textbox and radio button not selected) then it displays the suitable error messages on the page. But also the button uses the "openSessionPopup" function so that it opens up a pop up window which states the word "Session".
The problem is that when I click on the button it does both functions, so it displays validation errors if there is some and also opens up the pop up window.
What I want to do is that the pop up window should only be displayed after there are no validation errors. But I can't seem to get this to work, does anyone else know how to do this.
Below is my code:
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Create a Session</title>
<script type="text/javascript">
function validation() {
var btnRadioO = document.getElementsByName("sessionNo");
var isbtnRadioChecked = false;;
var dateTextO = document.getElementById("datepicker");
var timeTextO = document.getElementById("timepicker");
var errMsgO = document.getElementById("radioAlert");
var errDateTimeMsgO = document.getElementById("dateTimeAlert");
var errDateMsgO = document.getElementById("dateAlert");
var errTimeMsgO = document.getElementById("timeAlert");
for(i=0; i < btnRadioO.length; i++){
if(btnRadioO[i].checked){
isbtnRadioChecked = true;
}
}
if(!isbtnRadioChecked) {
errMsgO.innerHTML = "Please Select the Number of Sessions you Require";
} else {
errMsgO.innerHTML = "";
}
if (dateTextO.value == ''){
errDateMsgO.innerHTML = "Please Select a Date";
}else{
errDateMsgO.innerHTML = "";
}
if (timeTextO.value == ''){
errTimeMsgO.innerHTML = "Please Select a Time";
}else{
errTimeMsgO.innerHTML = "";
}
}
function openSessionPopup (session) {
window.open(session,
'window',
'width=500,height=500,scrollbars=yes,status=no');
}
</script>
</head>
<body>
<form action="create_session.php" method="post">
<table>
<tr>
<th>Number of Sessions :</th>
<td class="sessionNo"><input type="radio" name="sessionNo" value="1" />1</td>
<td class="sessionNo"><input type="radio" name="sessionNo" value="2" />2</td>
<td class="sessionNo"><input type="radio" name="sessionNo" value="3" />3</td>
<td class="sessionNo"><input type="radio" name="sessionNo" value="4" />4</td>
<td class="sessionNo"><input type="radio" name="sessionNo" value="5" />5</td>
</tr>
</table>
<div id="radioAlert"></div>
<p><input type="text" id="datepicker" >
<br/><span id="dateAlert"></span></p>
<p><input type="text" id="timepicker" >
<br/><span id="dateTimeAlert"></span><span id="timeAlert"></span></p>
<p><input class="questionBtn" type="button" value="Prepare Questions" name="prequestion" onClick="validation();openSessionPopup(this.href); return false" /></p>
</form>
</body>
First you should move your event handlers out of your html markup.
Next you should bind an event handler to that click event.
After that you should modify your validation method to return true or false to denote if it passed validation or not.
Last you should use that validation result in a conditional wrapping your showpopup method invocation.
Something like
function myClickHandler(){
if(validation()){
showSessionPopup();
}
}
for your handler and this how how you would bind it
document.getElementsByName("prequestion")[0].addEventListener('click', myClickHandler);
Finally you would modify your validation method like so
function validation() {
var result = true;
var btnRadioO = document.getElementsByName("sessionNo");
var isbtnRadioChecked = false;;
var dateTextO = document.getElementById("datepicker");
var timeTextO = document.getElementById("timepicker");
var errMsgO = document.getElementById("radioAlert");
var errDateTimeMsgO = document.getElementById("dateTimeAlert");
var errDateMsgO = document.getElementById("dateAlert");
var errTimeMsgO = document.getElementById("timeAlert");
for(i=0; i < btnRadioO.length; i++){
if(btnRadioO[i].checked){
isbtnRadioChecked = true;
}
}
if(!isbtnRadioChecked) {
errMsgO.innerHTML = "Please Select the Number of Sessions you Require";
result = false;
} else {
errMsgO.innerHTML = "";
}
if (dateTextO.value == ''){
result = false;
errDateMsgO.innerHTML = "Please Select a Date";
}else{
errDateMsgO.innerHTML = "";
}
if (timeTextO.value == ''){
errTimeMsgO.innerHTML = "Please Select a Time";
result = false;
}else{
errTimeMsgO.innerHTML = "";
}
return result;
}
This will make your validation() method return false if you have errors.

Categories