I have a table with a list of customers and its ids. The table content will change (I load data from database).
<table name="myCustomers">
<thead>
<tr><th>Name</th></tr>
</thead>
<tbody>
<tr>
<td>Name1</td>
<input type="hidden" value="1" />
</tr>
<tr>
<td>Name2</td>
<input type="hidden" value="2" />
</tr>
<tr>
<td>Name3</td>
<input type="hidden" value="3" />
</tr>
</tbody>
<table>
My page name is test.cfm
I would like, using JavaScript or JQuery, to refresh the page every 10 seconds, but passing the input hidden value as parameter. For example, first it load the page. Then, after 10 seconds, call test.cfm?myID=1... 10 seconds later, test.cfm?myID=2 and so on.
Is it possible using JavaScript or JQuery?
Thanks
Try writing something in JavaScript to grab data from the web server every ten seconds and print it to the table using innerHTML. Method for getting data from server depends on the format of course.
// Gets any query string variable
function qs(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
// Gets your specific query string variable and parses it as an int
function getQueryStringId() {
var id = parseInt(qs("myId"), 10);
return isNaN(id) ? 0 : id;
}
// Does the redirect/refresh after 10 seconds
function init() {
var baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
var currentId = getQueryStringId();
var nextId = currentId + 1;
var nextUrl = baseUrl + "?myId=" + nextId;
window.setTimeout(function () {
window.location.href = nextUrl;
}, 1000);
}
init();
<html>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
</head>
<body>
<form>
<table name="myCustomers">
<thead>
<tr><th>Name</th></tr>
</thead>
<tbody>
<tr>
<td>Name1</td>
<input type="hidden" value="12" />
</tr>
<tr>
<td>Name2</td>
<input type="hidden" value="24"/>
</tr>
<tr>
<td>Name3</td>
<input type="hidden" value="35" class="key1"/>
</tr>
</tbody>
</form>
<table>
<script>
//use need to use cookie or session to keep track of page number
// create an array to store all form values
var col=0;
url();
var pageno;
function url(){
var values=[];
$("input").each(function(){
// insert form value into array
values.push($(this).val());
});
var length=values.length;
var x = document.cookie;
var t = x.replace("username=","");
if(t==0){
document.cookie = "username="+0;
pageno=values[0];
var addr=location.pathname+"?pageid="+pageno;
window.location.replace(addr);
t++;
document.cookie = "username="+t;
}
else if(t<length){
pageno=values[t];
t++;
document.cookie = "username="+t;
var addr=location.pathname+"?pageid="+pageno;
window.location.replace(addr);
setTimeout(url,5000);
}
else{
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
}
</script>
</body>
</html>
Related
I've got a search box where as I type, table data gets filtered through and only matching results get shown. It works great; however, I want to make it better.
I want the code to ignore spaces and dashes. I'd prefer make it easy to add additional characters I want it to ignore as well in the future..
For instance...
Product Table
FH-54
TDN 256
TDN25678
FH54
In the search box, if I type FH54, I'd like both the FH-54 and the FH54 to show up. If I type in FH-54 I'd also like the FH54 and the FH-54 to show up and so on to include FH 54 as well.
If I type in TDN2 or TDN 2 in the search box, I'd like TDN 256 and TDN25678 to show up.
<b>Product Search</b><br /><form class="formatted">
<input id="Search" data-class="search_product" type="text" /></form>
<script type="text/javascript">
$('#Search').on('keyup', function(e) {
$("#noData").remove();
var value = $(this).val();
value = value.replace(/\\/g, '');
var patt = new RegExp(value, "i");
var sw = 0;
var counter = 0;
$('#Data tbody').find('tr').each(function() {
counter++;
if (!($(this).find('td').text().search(patt) >= 0)) {
$(this).not('#header').hide();
sw++;
} else if (($(this).find('td').text().search(patt) >= 0)) {
$(this).show();
}
});
if (sw == counter) {
$("#Data tbody").append(`<tr id="noData">
<td colspan="3">No data</td>
</tr>`);
} else {
$("#noData").remove();
}
});
</script>
I've tried to reconstruct your scenario the best I could and made a working example.
As per your requirement to ignore all spaces and dashes: How about removing spaces and dashes from search string and from your values within the columns?
$('#Search').on('keyup', function(e) {
$("#noData").remove();
var value = $(this).val();
var spacesAndDashes = /\s|-/g;
value = value.replace(spacesAndDashes, "");
var patt = new RegExp(value, "i");
var sw = 0;
var counter = 0;
$('#Data tbody').find('tr').each(function() {
counter++;
if (!($(this).find('td').text().replace(spacesAndDashes, "").search(patt) >= 0)) {
$(this).not('#header').hide();
sw++;
} else if (($(this).find('td').text().replace(spacesAndDashes, "").search(patt) >= 0)) {
$(this).show();
}
});
if (sw == counter) {
$("#Data tbody").append(`<tr id="noData">
<td colspan="3">No data</td>
</tr>`);
} else {
$("#noData").remove();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b>Product Search</b>
<br />
<form class="formatted">
<input id="Search" data-class="search_product" type="text" />
</form>
<table id="Data">
<thead>
<tr>
<th>Product Table</th>
</tr>
</thead>
<tbody>
<tr>
<td>FH-54</td>
</tr>
<tr>
<td>TDN 256</td>
</tr>
<tr>
<td>FH54</td>
</tr>
<tr>
<td>FH 54</td>
</tr>
<tr>
<td>TDN25678</td>
</tr>
</tbody>
</table>
I am need of help. I am trying to figure out the below:
<script>
var ct = 1;
function new_bank()
{
ct++;
var div1 = document.createElement('div');
div1.id = ct;
// bank to delete extended form elements
var delLink = 'delete';
div1.innerHTML =
document.getElementById("newbanktpl").innerHTML + delLink;
document.getElementById('newbank').appendChild(div1);
}
// function to delete the newly added set of elements
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('newbank');
parentEle.removeChild(ele);
findTotalA();
}
</script>
<!-- Template -->
<div id="newbanktpl">
<table>
<tr>
<td></td>
<td><textarea name="BankAccount[]"></textarea></td>
<td><input type="number" onblur="findTotalA()" name="Value[]"/></td>
<td><input type="number" name="Ownership[]" /></td>
<td>**ADD DELETED LINK HERE** </td>
</tr>
</table>
what I am after is the delete function to be within the table - at the moment the delete function is after the newbanktpl, and I want in within... on the last ADD DELETED LINK HERE.
give the link in the template a class
clone the template
update the div's ID
assign the delIt function to the onclick of the link
give the link a data-delete attribute that references the ID to delete.
insert the clone after the last bank that was inserted
assign the clone as the new "last bank"
var ct = 1;
var tmpl = document.getElementById("newbanktpl");
var lastBank = tmpl;
function new_bank() {
var clone = tmpl.cloneNode(true);
clone.id = "bank_" + ct;
ct++;
var delLink = clone.querySelector(".delete_link");
delLink.setAttribute("data-delete", clone.id);
delLink.onclick = delIt;
lastBank.parentNode.insertBefore(clone, lastBank.nextSibling);
lastBank = clone;
}
// function to delete the newly added set of elements
function delIt() {
var id = this.getAttribute("data-delete");
var ele = document.getElementById(id);
if (ele === lastBank) {
lastBank = ele.previousElementSibling;
}
ele.parentNode.removeChild(ele);
// findTotalA();
}
#newbanktpl {
display: none;
}
<!-- Template -->
<div id="newbanktpl">
<table>
<tr>
<td></td>
<td><textarea name="BankAccount[]"></textarea></td>
<td><input type="number" onblur="findTotalA()" name="Value[]" /></td>
<td><input type="number" name="Ownership[]" /></td>
<td><a class="delete_link" href="#">delete</a></td>
</tr>
</table>
</div>
<button onclick="new_bank()">New Bank</button>
Try adding an id to your td, then you can use it in JS.
In your HTML
<table>
<tr>
...
<td>delete</td>
</tr>
</table>
In your script tag
...
document.getElementById("delete").href="javascript:delIt('+ ct +')";
...
The Entire function should look like this:
var ct = 1;
function new_bank() {
ct++;
var div1 = document.createElement('div');
div1.id = ct;
document.getElementById("delete").href="javascript:delIt('+ ct +')";
document.getElementById('newbank').appendChild(div1);
}
P.S. I don't know why you are trying to save bytes from the computer by calling variables with such short names, it's a waist of your time, it won't make any difference to the computer, but it makes it harder to understand your code.
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');
}
I have been given a code to modify for database records on a website using ajax.
I have the function correctly querying data but the table displayed does not get any of the records displayed with in it. I have code of the functions and the html below.
Please see this link of current version: http://www.eng.nene.ac.uk/~10406206/CSY2028/Ajax/Ajax.html
Function of loadrecords with a callback not sure why a callback is used
<script language="Javascript">
var xmlHttpReq = false;
var xmlHttpReq2 = false;
var xmlHttpReq3 = false;
function loadDatabaseRecordsCallback ()
{
if (xmlHttpReq.readyState == 4)
{
alert ("From Server (Load Records):List.php" + xmlHttpReq.responseText);
var record = xmlHttpReq.responseXML.getElementsByTagName('record');
var s = "";
for (var i = 0; i < record.length; i ++)
{
var rec = record[i];
var id = rec.getElementsByTagName("ID")[0].firstChild.data;
var carname = rec.getElementsByTagName("CARNAME")[0].firstChild.data;
var fueltype = rec.getElementsByTagName("FUELTYPE")[0].firstChild.data;
var transmission = rec.getElementsByTagName("TRANSMISSION")[0].firstChild.data;
var enginesize = rec.getElementsByTagName("ENGINESIZE")[0].firstChild.data;
var doors = rec.getElementsByTagName("DOORS")[0].firstChild.data;
var total = rec.getElementsByTagName("TOTAL")[0].firstChild.data;
var available = rec.getElementsByTagName("AVAILABLE")[0].firstChild.data;
appendRecord (id, carname, fueltype, transmission, enginesize, doors, total, available);
}
}
}
function loadDatabaseRecords ()
{
// Mozilla/Safari
if (window.XMLHttpRequest)
{
xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject)
{
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
alert ("To Server (Load Records): List.php");
xmlHttpReq.open('GET', "List.php", true);
xmlHttpReq.onreadystatechange = loadDatabaseRecordsCallback;
xmlHttpReq.send(null);
}
on the same page as the function is the table which is below
<body>
<form name="f1">
<input value="Load Database" type="button" onclick='JavaScript:loadDatabaseRecords()'></p>
</form>
<table id="DBTable" border="2">
<tr>
<td width="20">ID</td>
<td width="100">Car Name</td>
<td width="100">Fuel Type</td>
<td width="100">Transmission</td>
<td width="80">Engine size</td>
<td width="20">Doors</td>
<td width="20">Total</td>
<td width="20">Available</td>
</tr>
<form name="myform">
<tr>
<td><input type="text" name="id"></td>
<td><input type="text" name="carname"></td>
<td><input type="text" name="fueltype"></td>
<td><input type="text" name="transmission"></td>
<td><input type="text" name="enginesize"></td>
<td><input type="text" name="doors"></td>
<td><input type="text" name="total"></td>
<td><input type="text" name="available"></td>
<td colspan="2"><input type="button" value="add" onClick="JavaScript:addNewRecord()"></td>
<td colspan="2"><input type="checkbox" value="update" onClick="JavaScript:updateRecord()"></td>
<td colspan="2"><input type="checkbox" value="delete" onClick="JavaScript:deleteRecord()"></td>
</tr>
</form>
</table>
</body>
The function calls the List.php which is coded as follows
<?php
$link = mysql_connect ("194.81.104.22", "********", "*****");
mysql_select_db ("*******");
$query = "SELECT * from XYZ";
$result = mysql_query ($query);
for ($i = 0; $i < mysql_num_rows ($result); $i ++)
{
$row = mysql_fetch_object ($result);
print "<b>Car Name:</b> <i>$row->CARNAME</i><br>";
print "<b>Fuel Type:</b> <i>$row->FUELTYPE</i><br>";
print "<b>Transmission:</b> <i>$row->TRANSMISSION</i><br>";
print "<b>Total:</b> <i>$row->TOTAL</i><br>";
print "<b>Available:</b> <i>$row->AVAILABLE</i><br><br>";
}
mysql_close ($link);
?>
So, if you have seen the website you will see that you press the load database button and a box appears with all the database entries. However, once you press enter the table on the page remains empty.
My question is why?
can you explain to me where the problem is?
New to Ajax and apologies if I broke rules on posts it's my first one.
I am not clear with php, but I remember from my asp + ajax experiences:
You bring data back to your browser, but you should "re-paint" the page - you can do this in javascript, or may-be PHP has some ready solutions for this.
When you validated your method appendRecord receive valid values - find your table (DBTable) with javascript by id, and update the values of the row / columns by your record.
I'd recommend you to take a look on http://www.w3schools.com/php/php_ajax_database.asp
You bring data back to your browser, but you should "re-paint" the page - you can do this in javascript, or may-be PHP has some ready solutions for this.
When you validated your method appendRecord receive valid values - find your table (DBTable) with javascript by id, and update the values of the row / columns by your record.
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;
}