Pass value to popup window - javascript

I have some text field for send to popup window ( I want send productPrice and productName) :
<tr>
<form>
<td> ${product.getProductName()}</td>
<input type="hidden" name="productName" value=${product.getProductName()}>
<td>${product.getPrice()}</td>
<input type="hidden" name="productPrice" value=${product.getPrice()}>
<td>
<input type="button" onclick="makeOrder()" value="Make order"/>
</td>
</form>
</tr>
JS:
<script type="text/javascript">
function makeOrder(){
window.open("/user/makeOrder","","height=250,width=400,status=no,location=no,toolbar=no,directories=no,menubar=no");
}
How can I pass a variable ProductName and ProductPrice to popup window "/user/makeOrder" ?

You can pass ProductName and ProductPrice as query string to new location, then use search, .split(), while loop to set properties, values to an object.
function makeOrder(name, price){
window.open("/user/makeOrder?ProductName=" + name + "&ProductPrice=" + price,""
,"height=250,width=400,status=no,location=no,toolbar=no,directories=no,menubar=no");
}
At newly opended window
var params = location.search.split(/\?|=|&/).filter(Boolean);
var obj = {}, i = 0;
while (i < params.length) {
obj[params[i]] = params[++i];
++i;
}
console.log(obj)

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');
});
}

How to display array from local storage in html element?

Obviously, a beginner's question:
How do I get array data to display in an html element using html and javascript?
I'd like to display the user saved array data in a paragraph tag, list tag, or table tag, etc.
[http://www.mysamplecode.com/2012/04/html5-local-storage-session-tutorial.html]
Above is a link to the kindly provided example of localStorage except how to display the array on the html page rather than in the console.log.
Below is the code snip that demonstrates what I'm trying to do.
function saveArrayData() {
console.log("Saving array data to local storage.");
var myArrayObject = [];
var personObject1 = new Object();
personObject1.name = "Array1";
personObject1.age = 23;
myArrayObject.push(personObject1);
var personObject2 = new Object();
personObject2.name = "Array2";
personObject2.age = 24;
myArrayObject.push(personObject2);
var personObject3 = new Object();
personObject3.name = "Array3";
personObject3.age = 25;
myArrayObject.push(personObject3);
localStorage.setItem("persons", JSON.stringify(myArrayObject));
}
function restoreArrayData() {
console.log("Restoring array data from local storage.");
var myArrayObject = JSON.parse(localStorage.getItem("persons"));
for (var i = 0; i < myArrayObject.length; i++) {
var personObject = myArrayObject[i];
console.log("Name: " + personObject.name, "Age: " + personObject.age);
}
}
<label for="name">Name:</label>
<input type="text" data-clear-btn="true" name="name" id="name" value="">
<label for="age">Age:</label>
<input type="text" data-clear-btn="true" name="age" id="age" value="">
<br>
<br>
<input type="button" id="sArray" value="Save Array data" onclick="Javascript:saveArrayData()">
<input type="button" id="rArray" value="Restore Array data" onclick="Javascript:restoreArrayData()">
<p id="displayArrayDataHere"></p>
You should update your code like below:
function restoreArrayData() {
var myArrayObject = JSON.parse(localStorage.getItem("persons"));
$("#displayArrayDataHere").append("<table>");
myArrayObject.forEach(function(personObject) {
$("#displayArrayDataHere").append("<tr><td>"+personObject.name+"</td><td>"+personObject.age+"</td></tr>")
})
$("#displayArrayDataHere").append("</table>");
}

Knockout - Variable Value contains function body

When I try to access the values of the newly created elements, I get the function body as the variable values.
In the Fiddle,
Click "Add Name"
Enter First Name as "Kate" in the newly added row.
Click "Show All Names" button.
In the popup, function body gets displayed instead of "Kate". I am able to use the first element using name.FirstName and the rest of the elements using name.FirstName().
Is there any consistent way to get the value of FirstNamein this scenario (across the loop iterations)?
My HTML code is:
<table>
<tbody data-bind="foreach: names">
<tr>
<td>
<label>First Name:</label>
</td>
<td>
<input data-bind="value: FirstName" type="text">
</td>
<td>
<label>Last Name:</label>
</td>
<td>
<input data-bind="value: LastName" type="text">
</td>
</tr>
</tbody>
</table>
<button data-bind="click: addName">Add Name</button>
<button data-bind="click: showAllNames">Show All Names</button>
Javascript Code:
var namesArray = [{
"FirstName": "Tom",
"LastName": "Langdon"
}];
var ViewModel = function () {
var self = this;
self.names = ko.observableArray(namesArray);
self.CreateBlankName = function () {
return {
FirstName: ko.observable(""),
LastName: ko.observable("")
};
};
self.addName = function () {
names.push(CreateBlankName());
};
self.showAllNames = function () {
var namestring = "";
ko.utils.arrayForEach(self.names(), function (name) {
namestring += name.FirstName + "\n";
});
alert(namestring);
};
};
ko.applyBindings(ViewModel);
The fisrtname and lastName fields should be observables because you can changed through the UI.
So you need to turn these into ko.observables as follow :
var namesArray = [{
"FirstName": ko.observable("Tom"),
"LastName": ko.observable("Langdon")
}];
Now items will only have observables. That's why you need to change the showAllNames function :
ko.utils.arrayForEach(self.names(), function (name) {
namestring += name.FirstName() + "\n";
});
See fiddle
You can also automatically convert raw js object into observables object by using ko.mapping.fromJS function

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

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');
}

Edit functionality using javascript and local storage

Below is my code for dynamic generation of rows:
function addRow() {
var myName = document.getElementById("name");
var type = document.getElementById("type");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML=myName.value;
row.insertCell(1).innerHTML=type.value;
row.insertCell(2).innerHTML= '<input type="button" value = "Delete" onClick="Javascript:deleteRow(this)">';
row.insertCell(3).innerHTML= ' Edit';
}
and below is my code for popup after clicking on edit link:
<div class="popup">
<p>Please edit your details here</p>
<div>
<label for="firstname" id="attr_Name">Attribute Name</label>
<input type="text" id="firstname" value="" />
</div>
<div>
<label for="lastname" id="attr_Type">Attribute Type</label>
<select id="type1" ><option >Text</option><option >Paragraph</option><option >Dropdown</option></select>
</div>
<input type="button" id="button1" value="Save" onclick="saveEditedValues()"/>
<a class="close" href="#close"></a>
</div>
Now I am using local storage to save my edited values but I am not getting how to reflect it in the dynamically generated rows. Below is code for Local storage:
function saveEditedValues(){
var myName = document.getElementById("firstname").value;
alert(myName);
var type = document.getElementById("type1").value;
alert(type);
localStorage.setItem("attributeName",myName.value);
localStorage.setItem("attributeType",type.value);
var namevar1=localStorage.getItem("attributeName");
var namevar2=localStorage.getItem("attributeType");
}
Please provide some help
In order to update the table, the save function will need to be able to locate the correct row, which means you will have to pass it something like the row number.
When adding the row, define the onclick event handler of the Edit link to pass rowCount
row.insertCell(3).innerHTML= ' Edit';
Add a hidden input to your popup div
<input type="hidden" id="editingRow" />
and have the Edit function populate that value:
function Edit(rowNum) {
...
document.getElementById("editingRow").value = rowNum;
...
}
Then the saveEditedValues function can locate the row in the table and update the values
function saveEditedValues(){
...
var rowNum = document.getElementById("editingRow").value;
var row = document.getElementById("myTableData").rows[rowNum];
row.cells[0].innerHTML = myName;
row.cells[1].innerHTML = type;
...
}
like so: jsFiddle
var myName = document.getElementById("firstname").value;
alert(myName);
var type = document.getElementById("type1").value;
alert(type);
myName and type are the correct values (strings). So
localStorage.setItem("attributeName",myName.value);
localStorage.setItem("attributeType",type.value);
is wrong, you have to use the plain variables like this:
localStorage.setItem("attributeName",myName);
localStorage.setItem("attributeType",type);

Categories