jQuery: selected dropdown option returning undefined - javascript

I have a functionality where in a table, I can click an add button and a new tr gets prepended to the table. However, I want field AddOn to get disabled if a certain food category is selected. It is easy to tackle it on change but how to do it when I click on add and depending on the value originally selected in dropdown?
var index = 0;
var FoodCategory = "FoodCategory" + index;
var tr = '<tr class="row">' +
'<td></td>' +
'<td></td>' +
'<td><select id="' + FoodCategory + '" type="text" class="form-control" /><span id="FoodCat""></select></span></td>' +
'<td><span><select id="' + AddOns + '" class="form-control"></select></span><span id="AddOns"></span></td>' +
'</tr>';
("#tblFood").prepend(tr);
I'm trying to access the value of FoodCategory to disable the select of AddOns by
$('#'+FoodCategory).val() but it is not working.

Related

HTML Element not being inserted

I'm working on a .NET Core project for my company where work orders are loaded from our SQL database using Entity Framework, filtered and then displayed as markers on a map through Google Maps API for our installers.
We have two types of filters: one that gets included in an Ajax POST, and one that filters locally to decrease load times and performance issues. What I'm trying to do is load the local filter items (lists that are included in the response when calling the initial Ajax POST). If the list of filter items exceeds 5 items, I want them to collapse to only 5 items and insert an anchor which expands (utilizes jQuery's toggle()) showing the rest of the items in that list.
This is the excerpt from the JavaScript function which takes care of that:
filterItems
.forEach((filterItem, i) => {
var localItem = '<label class="' + selectorContainerClass
+ ' selectorContainer" id="' + selectorContainerIdPrefix + filterItem.key
+ '"><input id="' + convertValToEng(filterItem.value)
+ '" type = "checkbox" class="filled-in navy" name="' + inputName
+ '" value="' + filterItem.key
+ '" onchange="localFilter(this, this.value)" /><span class="selector-value">'
+ filterItem.value
+ '</span> <span id="' + paramName + 'Cnt__' + filterItem.key
+ '" class="selector-count"></span></label ><br />';
document.querySelector("#" + colId).insertAdjacentHTML('beforeend', localItem);
if (i >= 5) {
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key).addClass("collapse");
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key).toggle(100);
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key + " + br").toggle(100);
}
});
if (filterItems.length > 5) {
//TODO: Fix the bug here; the .filter-collapse element is not being inserted under local installers.
var newEl = '<a class="filter-collapse" onclick="toggleFilterExpand(false, this)";><i class="material-icons">expand_more</i></a>';
document.getElementById(colId).insertAdjacentHTML('beforeend', newEl);
}
I should be getting a newEl inserted under the "Installer" column (8 installers, 3 of them not being displayed), but I'm not. I've tried jQuery's after() and insertAfter() methods, but neither of those worked. newEl is being generated for the "Area" column, as it should, but for the "Installer" column it's not.
I've also tried inserting the element manually through the console window with the exact same code and it works.
Would appreciate some help with this as I feel lost regarding this issue.
Thanks.
It turned out to be a stupid mistake on my end where I was removing the element newEl from the all the other filter lists before inserting a new one to the currently iterated one.

Browser window shows correct value in inspector but invalid in the document

I am dynamically generating the input box using jquery and then embedding it into the document. The problem I am having is, although the correct value is being shown in the inspector, the browser shows an invalid value.
To be further clear, here is the image:
You can see that, in the inspector
<input name="txtTblAmount" class="num" style="width:70px;" type="text" value="1000" tabindex="29">
the value is 1000 while that being shown in the browser window is 1500. Can anyone please have a look and tell me, what's the problem here?
P.S: Have tried it in firefox as well. But still the problem is same i.e. different value in the inspector.
Here is the JS code:
function addrow(itemName, itemid, godown, godownid, quantity, rate, amount, gstAmount) {
gstAmount = typeof gstAmount !== 'undefined' ? gstAmount : '0';
if (typeof dTable1 != 'undefined') {
// dTable1.fnClearTable();
//$('#ItemRows').find('a[name="btnDelItem"]').off();
dTable1.fnDestroy();
// $('#ItemRows').empty();
}
//alert($('#ItemRows tr').length);
var strRow = '<tr id="row' + ($('#ItemRows tr').length + 1) + '">' +
'<td class="">' +
(($('#ItemRows tr').length + 1)) +
'</td>' +
'<td class="tdItemName" style="widtd: 250px">' +
itemName +
'<input name="hfItemId" style="width:200px;" type="hidden" value="' + itemid + '"/>' +
'</td>' +
'<td class="" style="widtd: 200px">' +
godown +
'<input name="hfGodownid" style="width:200px;" type="hidden" value="' + godownid + '"/>' +
'</td>' +
'<td class="" style="widtd: 200px">' +
'<input name="txtTblQuantity" style="width:200px;" class="num" type="text" value="' + quantity + '"/>' +
'</td>' +
'<td class="" style="widtd: auto">' +
'<input name="txtTblRate" style="width:70px;" class="num" type="text" value="' + rate + '"/>' +
'</td>' +
'<td class="" style="widtd: auto">' +
'<input name="txtTblAmount" class="num" style="width:70px;" type="text" value="' + amount + '"/>' +
'</td>' +
'<td>' +
'<input name="txtTblGstAmount" class="num" style="width:70px;" type="text" value="' + gstAmount + '"/>' +
'</td>' +
'<td class="ms"><div class="btn-group1"> <a class="btn btn-small" rel="tooltip" data-placement="left" data-original-title=" edit " name="btnDelItem" data-id="' + ($('#ItemRows tr').length + 1) + '" ><i class="icon-remove"></i></a> </div></td>' +
'</tr>';
console.log(strRow);
console.log(amount);
$('#ItemRows').append(strRow);
//SaveNewParty($("#drpAccId option:selected").text());
bindGrid();
//dTable1.fnDraw();
PopulateTotal();
// $('#ItemRows').find('a[name="btnDelItem"]').off();
var insertedRow = $('#ItemRows tr')[$('#ItemRows tr').length - 1];
$(insertedRow).find('a[name="btnDelItem"]').on('click', function () {
var row = $(this).parents('tr');
dTable1.fnDeleteRow(dTable1.fnGetPosition(row[0]));
$('#ItemRows tr').each(function (index) {
$(this).find('td:nth(0)').text((index + 1));
});
PopulateTotal();
})
$('#datatable_Items').css('width', '100%');
Populate_Events();
}
I just had a look at your code and found that there was no problem in the code you have shown us here. I agree with Afzaal Ahmad Zeeshan but the way he has explained it, it's not always the case. I recently had the same issue and after hours of scratching my head I found out that the value was being changed by some other jquery code.
Also note that, it is not always the case that the value set by the jquery is shown in the inspector for example, if you try $("#inputel").val(4), you will note that the value will not be updated in the inspector but in the backend this value has been updated. Inspector only shows the value that was sent from the server, not the one you set by jquery or something else.
Hope you got my point!
Kamran, that's of no importance. You are setting this value NOT DYNAMICALLY. Yes, you can see here! You are either setting this value while loading the page, or you are using some other code, that you are not showing us! I am not sure of that. Ok here.
In my example you can see, I am writing a text in the input but there is no value update in the element's inspection.
Also, its maybe not the answer but you can see that you're using widtd which is not a correct CSS property. The correct one is width. You know that.
I am sure you won't get any problem while sending the form to the server, as the value will get updated by the value that you just wrote.
I have seen your code, you are writing the field as:
<input name="txtTblAmount" class="num"
style="width:70px;" type="text" value="' + amount + '"/>'
According to me, the issue is at amount. You are havin this field in the function too.
function addrow(itemName, itemid, godown,
godownid, quantity, rate, amount, gstAmount) {
Now what you can do to prevent that is to change the value of amount there. If you donot want to change it, then its OK. And also, once again you should not fear this value difference, as once you click submit the value that you have entered will be sent to the server instead of value of the field itself. The value is just because you have it written there. Nothing else, so don't worry! Its ok. You cannot change the value now, if you want to. Then here is the hell code, you will have to hard code it. Like this!
<div id="input">
<input type="text" id="text" value="" onkeyup="updateVal()" />
</div>
function updateVal() {
// start function..
var val = $('#text').val(); // the value of field..
// after getting the value, update the div..
$('#input').html("<input type='text' id='text' value='" +
val + "' onkeyup='updateVal()' />");
}
But note, after using this code, you will get the current value in the field! But you will loose the focus on the input field. As the div will get updated but the values will be the newest ones!
Now to keep in focus?
You can use this:
$('#text').focus();
But while using this, you will get only one ONLY ONE word in the field.
Why?
Because once if will focus on the field, it will (select all) select the words or value inside the field and when you press another word, it will replace the previous one with the latest one! This way you will not get any correct field I mean the field of your choice! But you issue will be fixed.
So kamran believe me, let it be the way it is! You donot want to hard-code it. If you still wanna give it a try, use the code I shared!
Example for the code I am sharing is as under:
Now when you right the value or some words, you will get the value auto updated when you see this Developer Tools. Like this:
That was all. I gave you two options for your work. And still I will love to go with the option of Not using a code, to just update the value on the field. Rest is upto you Kamran.
Edit:
You mentioed that you want to use the value 1000 not the value that the user would add to the input. Then use this:
$("name='txtTblAmount'").val() == "1000");
This will automatically override the value that user will add and replace it with the value that you want to get!

hide a table td using Jquery

In the following code how can i hide the id column of the table.
var joblist = "";
joblist = joblist + "<table ><tr><th >Select</th><th id='td_1'>ID</th><th >Name</th><th >Names</th><th>OS</th><th >Server</th></tr>";
var tabString = '<tr ><td > ' + '<input type="radio" name="joblist" onclick="myfunc(this);" id= ' + value.jobid + 'value=' + value.jobid + '> </td><td id="td_1" >' + value._id + '</td><td >' + value.names + '</td><td a>' + value.os + '</td><td >' + value.server + '</td></tr>';
joblist = joblist + tabString;
I tried
$("#td_1").hide()
But it is not working.Any other solutions?
First of all if there is multiple td then don't use same id, in this case add some other post or pre. And use as
$('[id^="td_1"]').hide();//for post
$('[id$="td_1"]').hide();//pre
Try this
$('[id="td_1"]').hide();
First of all ID must be unique. you have declared same ID for TH and TD
$("#your_td_id").hide();
if you more than one TD then use class instead of ID.
As others have mentioned, you cannot match multiple elements based purely on an ID; they must be unique across the entire document. I suspect that what you are seeing is the 'ID' heading disappearing from the top of your table, but the values remaining visible later on in the table.
Other answers have mentioned switching to a class; there is another alternative available, using the nth-child pseudo-selector:
$("table tr > *:nth-child(2)").hide();
This will hide the 2nd element immediately under tr, as * matches both the TH and the TD. If you never want it visible, then better solutions include CSS:
table tr > *:nth-child(2) { display: none; }
or simply rendering it into an <input type='hidden' /> instead and including it in one of your existing cells (e.g. alongside the radio button).
Note that you have a few additional errors in your HTML, including:
<td a>' + value.os +
that you may want to investigate at the same time.
Before hiding an element you must assign it to DOM. If you want to hide multiple elements you must use class attribute instead of id
var joblist = "";
joblist = joblist + "<table ><tr><th >Select</th><th class='td_1'>ID</th>" +
"<th >Name</th><th >Names</th><th>OS</th><th >Server</th></tr>";
var tabString = '<tr ><td > ' + '<input type="radio" name="joblist"
onclick="myfunc(this);" id= ' + value.jobid + 'value=' +
value.jobid + '> </td><td class="td_1" >' + value._id +
'</td><td >'+ value.names + '</td><td a>' + value.os +
'</td><td >' + value.server + '</td></tr>';
joblist = joblist + tabString;
$('#myElement').append(joblist);
$('.td_1').hide();

Javascript selected item value not pulling correctly

I'm doing a select box with a list of items(dynamically created from an XML created by a webservice), and I'm unable to pull the selected value correctly. Here is what is happening.
What I'm sending:
onchange="changeFunction(this.options[this.selectedIndex].value)"
What I'm receiving:
function (a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!=
I'm the only thing I'm using is some self built functions and jQuery.
Any help would be superb.
Edit: here is the change function. All it is intended to do is build a form populated with values for given selected item.
function changeFunction(selection) {
console.log(selection);
$('#right').empty();
var addNewFields = 'these will be the fields';
$('#right').append(addNewFields);
}
Here is the select in question:
<select class="userSelection" id="userSelection" size="10" style="width:150px;" onchange="changeFunction(this.options[this.selectedIndex].value)"></select>
This is literally all the code in the html part of it. It's being populated via ajax, and there are 2 divs, one for left, containing the select, and one for right, containing the content for the user.
Just for giggles, here is the code creating the options:
var optionTag = '<option value="' + $(this).find('optionID').text + '" >' + $(this).find('optionName').text() + '</option>';
$('#userSelection').append(optionTag);
var optionTag = '<option value="' + $(this).find('optionID').text + '" >' + $(this).find('optionName').text() + '</option>';
should be:
var optionTag = '<option value="' + $(this).find('optionID').text() + '" >' + $(this).find('optionName').text() + '</option>';
Notice that $(this).find('optionID').text should be $(this).find('optionID').text().
or even better, to avoid this soup:
var optionTag = $('<option/>', {
value: $(this).find('optionID').text(),
html: $(this).find('optionName').text()
});
When you set the event handler of a DOM object to a function it get passed an event object as it's argument.
selectBox.onchange = function(event) {
changeFn(this.options[this.selectedIndex].value);
};

Dynamically adding dijit on button click programatically...how?

I've got a problem with another dojo enabled form that I am working on. A user can enter details onto the page by entering the data using a dialog box, which in turn updates the database and then displays the user data entered on to the form.
Each element added consist of 2 x Validation Text boxes 1 x FilteringSelect. When it's added to the page they are added as simply text boxes.
I've tried just adding as standard strings but that means the dojo.parse() does not run on the code. I've also tried programmatically adding the elements but that just displays the element object as a string to the page. So far I have:
var xhrArgs = {
url: url,
handleAs: "text",
preventCache: true,
load: function(data){
var idResult = parseInt(data);
if(idResult > 0){
var divStr = '<div id="employ_' + idResult + '" style="float:left;width:100%;">' +
'<table width="300">' +
'<tr>' +
'<td height="29"><Strong>' +
'<input type="text" dojoType="dijit.form.ValidationTextBox ' +
'change="markEmploymentForUpdate(); ' +
'id="cmpy_'+ idResult +'" '+
'required="true" ' +
'promptMessage="Please enter a valid company name" ' +
'invalidMessage="please enter a valid company name" ' +
'trim="true"' +
'value="'+ companyname +'"/>' +
'</td>' +
'<td height="29"><input dojoType="dijit.form.FilteringSelect" store="rolestore" searchAttr="name" name="role" onchange="markEmploymentForUpdate();" id="roleInput_'+ idResult +'" value="'+ jobrole +'" ></td>' +
'<td height="29">' +
'<input type="text" dojoType="dijit.form.ValidationTextBox" onchange="markEmploymentForUpdate();"' +
'id="jtitle_'+ idResult + '"' +
'required="true"' +
'promptMessage="Please enter your job title"' +
'invalidMessage="Please enter your job title"' +
'value="'+ jobtitle + '"/>' +
'</td>' +
'<td height="29"><img src="/images/site/msg/small/msg-remove-small.png" border="0" onmouseover="this.style.cursor=\'pointer\';" onclick="removeEmployer(\'employ_'+ idResult +'\', '+ idResult +')" /></td>' +
'</tr>' +
'</table>' +
'</div>';
dijit.byId('companydetails').hide();
dijit.byId('employername').setValue('');
dijit.byId('jobtitle').setValue('');
dijit.byId('jobrole').setValue('');
dojo.byId('data-table').innerHTML += divStr;
dojo.byId('companydetails').hide();
}else{
dojo.byId('add-error').innerHTML = '<div class="error">Unable to process your request. Please try again.</div>';
}
}
};
var deferred = dojo.xhrGet(xhrArgs);
This is displaying text boxes as the dojo.parse isn't running on this. If I replace the ValidationTextBox with:
var textbox = new dijit.form.ValidationTextBox({
id:"cmpy_" + idResult,
required:true,
trim:true,
"change":"markEmploymentForUpdate();",
promptMessage:"Please enter a valid company name",
value:companyname
});
I just get the object printed to the page.
Any ideas how I can added this to my page and maintain the dojo component rather than it defaulting to a text box?
Many thanks.
dojo.parser.parse(dojo.byId('data-table')); after you set it's innerHTML

Categories

Resources