jQuery workflow - javascript

I have two fields Course name and Course code, the values of this name and course are "Master of Arts" and "MA", am trying to update these fields, for this am calling the jQuery function,
function updateData(obj) {
var id = obj.id.split("_"); //here the value of id is "id[1,1,CODE]"
var objId = id[0]; //objId=1
var type = id[1]; //type=1
var objUpdate = new Object();
objUpdate.Id = objId;
objUpdate.Name = $("#" + objId + "_" + type + "_NAME").val();
objUpdate.Code = $("#" + objId + "_" + type + "_CODE").val();
}
after the execution of objUpdate.Name the value is coming as "Master of Arts" and objUpdate.Code as "MA".
how its getting the name and code, can anyone explain this.
the HTML am using here is
<table class='acListTable' id='#ID#TYPE'>
<tr>
<td>
<input type='text' class='acEditBox' id='#ID_#TYPE_NAME' value='#NAME'/>
</td>
</tr>
<tr>
<td>
<input type='text' class='acEditBox' id='#ID_#TYPE_CODE' value='#CODE'/>
</td>
</tr>
</table>

Related

Show the correct input file name in a dynamic table

I have a simple add function in my table.
I would like to post the name of each uploaded file on the table, but it seems like it's only working on the first 2 rows due to my var i = 0; is not working properly.
Here is my code:
<table id='datarows'>
<tr>
<td>Upload</td><td>Filename</td>
</tr>
<tr>
<td><input type="file" id="ProductImage" name="ProductImage0" onchange="getFileData(this);"/></td>
<td><input id="filename" name="filename0" type="text" /></td>
</tr>
</table>
ADD NEW PRODUCT<br />
<script>
var i = 0;
function addProduct() {
var str = '<tr><td><input type="file" id="ProductImage'+i+'"
name="ProductImage'+i+'" onchange="getFileData2(this);" /></td>'
str = str + '<td ><input id="filename'+i+'" name="filename'+i+'" type="text"
/></td></tr>';
$('#datterrows').append(str);
}
//----- Upload picture/file and add name table 1
function getFileData(myFile) {
var file = document.getElementById("ProductImage").value;
var msg = document.getElementById("filename");
msg.value = "test"+file;
}
//----- Upload picture/file and add name table 2
function getFileData2(myFile) {
var file = document.getElementById("ProductImage"+i).value;
var msg = document.getElementById("filename"+i);
msg.value = "test" + file;
}
</script>
I don't get any errors but all I see is the my input id keeps repeating it self to be productimage0 and not continuing for each element I add.
I hope someone can help, it's been pain in the a**

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

jquery efficient way to select tablerow data

I have a table with multiple rows of the same pattern:
<tr role="row" class="even">
<td><input type="checkbox" id="valj4"></td>
<td>Generell grupp</td>
<td>IKT Ipad11- Mirko</td>
<td>Grundinställningar</td>
</tr>
Each row has a checkbox with unique ID, what would be the most efficient way to get a list of UUIDs for the rows with a checked checkbox. I would like to use jQuery.
$(function() {
var texts = [];
$('tr td:has(input:checkbox:checked) ~ td > a').each(function(i, e) {
texts.push($(e).attr('href'));
});
$('#result').html(texts.join('<br/>'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr role="row" class="even">
<td>
<input type="checkbox" id="valj4" checked>
</td>
<td>Generell grupp</td>
<td>IKT Ipad11- Mirko (...5)
</td>
<td>Grundinställningar</td>
</tr>
<tr role="row" class="even">
<td>
<input type="checkbox" id="valj4">
</td>
<td>Generell grupp</td>
<td>IKT Ipad11- Mirko (...6)
</td>
<td>Grundinställningar</td>
</tr>
<tr role="row" class="even">
<td>
<input type="checkbox" id="valj4" checked>
</td>
<td>Generell grupp</td>
<td>IKT Ipad11- Mirko (...7)
</td>
<td>Grundinställningar</td>
</tr>
</table>
<div id="result"/>
Getting the UUID is then an easy exercise in string chopping.
I assume your table has an id and it's "#table-id":
$("#table-id").find(":checked")
would get you all the checked checkboxes and radio boxes.
$("#table-id").find("input[type='checkbox']:checked")
would get you all the checked checkboxes.
var ids = "";
$("#table-id").find("input[type='checkbox']:checked").each(function(){
ids += $(this).attr("id") + ",";
});
would give you a comma seperated list containing the ids of checked checkboxes in the table.
and the UUIDS list:
var UUIDs = "";
$("#table-id").find("input[type='checkbox']:checked").each(function(){
var href = $(this).closest("tr").find("td > a").first().attr("href");
var UUID = href.split('?')[1];
UUIDS += UUID + ",";
});
I would try the following
var ids = [];
$("#table input:checkbox:checked").each(function () {
var uuid = getParameter($(this).closest('tr').find('a').eq(0).attr('href'))
ids.push(uuid);
});
function getParameter(url) {
var regex = new RegExp("[\\?&]uuid=([^&#]*)"),
results = regex.exec(url);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
where #table is the id of your table
Example
jQuery('#formId').find('tr[class=even]').each(function () {
var rowId = "";
this.find('input[type=checkbox]').each(function() {
if(this.checked) {
rowId = "row" + $(this).val();
}
});
$(this).attr('id', rowId);
});
Create a new list of UUIDs.
var listOfUUIDs = [];
Get the checked input, go up to grandparent (the tr), then find the a inside it.
Go through the list of a's, adding UUIDs to the list.
$("tr input[checked=checked]").parent().parent().find("td a").each(function(){
listOfUUIDs.push(
$(this).prop('href').substr(indexOf("uuid=") + 5)
)
});
This should give you what you need.
$('tr').each(function(index) {
var $this = $(this),
input = $this.find('input'),
result = '';
if ( input.is(':checked') ) {
var uuid = $this.find('a').attr('href').replace(/^\/Home\/DeviceDetails\?uuid=/g, ""),
result = result + index + '. ' + input.attr('id') + ' has the uuid: ' + uuid + '<br />';
}
$('#result').html(result);
});
try this
$( "input[type=checkbox]" ).change(function() {
if($(this).is(":checked")) {
alert($(this).attr("id"));
}
});

Selecting data out of the nth td element

I'm attempting to get the data("borgid") out of the following html:
<tr style="cursor:default;" class="odd">
<td class=" ">1</td>
<td class=" ">What was your favorite childhood pet's name?</td>
<td data-borgid="1" class=" ">Generic Hospital Networks</td>
<td class=" ">5173</td>
<td style="text-align:right;" class=" "><input type="button" value="Remove" name="1" class="deleteMeCQ" style="cursor:pointer;"></td>
</tr>
I have tried both $(':nth-child(2)', $(this)).data("borgid") and $tds.eq(2).data("borgid"). Both return "undefined". Thanks in advance.
See also: Is there a way to combine $(this) with :nth-child?
var a = [];
$("#ChallengeQuestionsTable tbody tr").each(function () {
var $tds = $(this).children('td');
var questionid = '';
var question = '';
var borgid = '';
if ($tds.length == 5) {
questionid = $tds.eq(0).html();
question = $tds.eq(1).html();
borgid = $(':nth-child(2)', $(this)).data("Borgid");
a.push('{ "questionid" : "' + questionid + '", "question" : "' + question + '", "borgid" : "' + borgid + '" }');
}
});
If you want to get borgid, you can select by existing attribute:
borgid = $($(this).find("[data-borgid]").get(0)).attr("data-borgid");
In general if you want to select the nth td you could go with
$("td:eq(1)")
e.g. to select the second td.
If you want to iterate over all <tr> and its <td> and say, you want to select the 2nd one, you would do it as follows:
$("tbody").find("tr").each(function(){
$(this).find("td:eq(1)").html("changed")
};
Here is a Fiddle to play with. And here is the documentation of :eq().
Does this work, if you grab the data by an attribute selector?
var borgid = $(this).find("td[data-borgid]").data("borgid");
It could also be beneficial to avoid ":nth-child", shall you change your HTML later.

Knockout JS: Binding Dynamic Rows

I'm having some trouble in binding dynamically created dom elements
Code:
var i=0;
$.each(data.info, function(index, element) {
$("#div1").append("<tr><td>" + element.Name + "</td><td>"+ element.Major +"</td><td>" + element.Sex +"</td><td>" + "<input data-bind='value: eng"+i+"' ></td><td>" + "<input data-bind='value: jap"+i+"' ></td><td>" + "<input data-bind='value: cal"+i+"' ></td><td>" + "<input data-bind='value: geo"+i+"' ></td><td>" + "<strong data-bind='text: total'></td>" )
i++;
});
This creates row with input data-bind values eng0, eng1, jap0, jap1, etc.
I want to bind these as observables
Code
function AppViewModel() {
this.eng = ko.observable(element.English);
this.jap = ko.observable(element.Japanese);
this.cal = ko.observable(element.Calculus);
this.geo = ko.observable(element.Geometry);
this.total = ko.computed(function() {
var tot=parseFloat(this.eng()) + parseFloat(this.jap()) + parseFloat(this.cal()) + parseFloat(this.geo());
return (tot);
}, this);
}
ko.applyBindings(new AppViewModel());
This code is also inside $.each(data.info, function(index, element){}
I want some thing like
Var i=0;
$.each(data.info, function(index, element) {
function AppViewModel() {
this.eng+i = ko.observable(element.English);
this.jap+i = ko.observable(element.Japanese);
this.cal+i = ko.observable(element.Calculus);
this.geo+i = ko.observable(element.Geometry);
this.total+i = ko.computed(function() {
var tot=parseFloat(this.eng()) + parseFloat(this.jap()) + parseFloat(this.cal()) + parseFloat(this.geo());
return (tot);
}, this);
}
i++;
}
That get me result this.eng0 = ko.observable()
Note: the data is obtained from a JSON object. I have only included the iteration path
May I suggest that using a foreach binding may be better than using jQuery's each and generating the HTML yourself? I'd suggest changing your view model to something like this:
function AppViewModel() {
this.items = ko.observableArray();
}
function ItemViewModel(element) {
this.eng = ko.observable(element.English);
this.jap = ko.observable(element.Japanese);
this.cal = ko.observable(element.Calculus);
this.geo = ko.observable(element.Geometry);
this.name = ko.observable(element.name);
this.major = ko.observable(element.major);
this.sex = ko.observable(element.sex);
this.total = ko.computed(function () {
var tot = parseFloat(this.eng()) + parseFloat(this.jap()) + parseFloat(this.cal()) + parseFloat(this.geo());
return (tot);
}, this);
};
Here, the AppViewModel is a container for the list of elements, and each element is its own ItemViewModel, with the properties you seem to have.
The html to bind this would be something like this:
<table>
<tbody data-bind="foreach: items">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: major"></td>
<td data-bind="text: sex"></td>
<td><input data-bind='value: eng' /></td>
<td><input data-bind='value: jap' /></td>
<td><input data-bind='value: cal' /></td>
<td><input data-bind='value: geo' /></td>
<td><strong data-bind='text: total' /></td>
</tr>
</tbody>
</table>
When you get the JSON from your server you can use Knockout's built-in JSON stuff, the mapping plugin, or parse them yourself. I created an example using the latter option in this jsfiddle.

Categories