Getting value from input control using jQuery - javascript

I am using the teleriks treeview control (asp.net mvc extensions), where I may have up to three children nodes, like so (drumroll...... awesome diagram below):
it has its own formatting, looking a bit like this:
<%=
Html.Telerik().TreeView()
.Name("TreeView")
.BindTo(Model, mappings =>
{
mappings.For<Node1>(binding => binding
.ItemDataBound((item, Node1) =>
{
item.Text = Node1.Property1;
item.Value = Node1.ID.ToString();
})
.Children(Node1 => Node1.AssocProperty));
mappings.For<Node2>(binding => binding
.ItemDataBound((item, Node2) =>
{
item.Text = Node2.Property1;
item.Value = Node2.ID.ToString();
})
.Children(Node2 => Node2.AssocProperty));
mappings.For<Node3>(binding => binding
.ItemDataBound((item, Node3) =>
{
item.Text = Node3.Property1;
item.Value = Node3.ID.ToString();
}));
})
%>
which causes it to render like this. I find it unsual that when I set the value it is rendered in a hidden input ? But anyway:...
<li class="t-item">
<div class="t-mid">
<span class="t-icon t-plus"></span>
<span class="t-in">Node 1</span>
<input class="t-input" name="itemValue" type="hidden" value="6" /></div>
<ul class="t-group" style="display:none">
<li class="t-item t-last">
<div class="t-top t-bot">
<span class="t-icon t-plus"></span>
<span class="t-in">Node 1.1</span>
<input class="t-input" name="itemValue" type="hidden" value="207" />
</div>
<ul class="t-group" style="display:none">
<li class="t-item">
<div class="t-top">
<span class="t-in">Node 1.1.1</span>
<input class="t-input" name="itemValue" type="hidden" value="1452" />
</div>
</li>
<li class="t-item t-last">
<div class="t-bot">
<span class="t-in">Node 1.1.2</span>
<input class="t-input" name="itemValue" type="hidden" value="1453" />
</div>
</li>
</ul>
</li>
</ul>
What I am doing is updating a div after the user clicks on a certain node. But when the user clicks on a node, I want to send the ID not the Node text property. Which means I have to get it out of the value in these type lines <input class="t-input" name="itemValue" type="hidden" value="1453" />, but it can be nested differently each time, so the existing code I ahve doesn't ALWAYS work:
<script type="text/javascript">
function TreeView_onSelect(e) {
//`this` is the DOM element of the treeview
var treeview = $(this).data('tTreeView');
var nodeElement = e.item;
var id = e.item.children[0].children[2].value;
...
</script>
So based on that, what is a better way to get the appropriate id each time with javascript/jquery?
edit:
Sorry to clarify a few things
1) Yes, I am handling clicks to the lis of the tree & want to find the value of the nested hidden input field. As you can see, from the telerik code, setting item.Value = Node2.ID.ToString(); caused it to render in a hidden input field.
I am responding to clicks anywhere in the tree, therefore I cannot use my existing code, which relied on a set relationship (it would work for first nodes (Node 1) not for anything nested below)
What I want is, whenever there is something like this, representing a node, which is then clicked:
<li class="t-item t-last">
<div class="t-bot">
<span class="t-in">Node 1.1.2</span>
<input class="t-input" name="itemValue" type="hidden" value="1453" />
</div>
</li>
I want the ID value out of the input, in this case 1453.
Hope this now makes a lot more sense.
if possible would love to extend this to also store in a variable how nested the element that is clicked is, i.e. if Node 1.1.2 is clicked return 2, Node 1.1 return 1 and node 1 returns 0

It's a little unclear what you're asking, but based on your snippet of JavaScript, I'm guessing that you're handling clicks to the lis of the tree & want to find the value of the nested hidden field? If so, you want something like this:
function TreeView_onSelect(e) {
var id = $(e.item).find(".t-input:first").val();
}
Edit: In answer to your follow-up question, you should be able to get the tree depth with the following:
var depth = $(e.item).parents(".t-item").length;

In jQuery you can return any form element value using .val();
$(this).val(); // would return value of the 'this' element.
I'm not sure why you are using the same hidden input field name "itemValue", but if you can give a little more clarity about what you are asking I'm sure it's not too difficult.

$('.t-input').live('change',function(){
var ID_in_question=$(this).val();
});

Related

How to iterate through ul elements within a div and hide them individually on a submit?

In my node app using express I have a view function that creates a list of inactive companies, each company has two submit input types "Active" and "Delete". I would like to be able to hit submit and have that individual ul become hidden. However, I'm not quite sure how to iterate over individually. Every time I've tried I end up hiding all the elements. Here's my view function:
function inactiveFiltered(companyObject) {
return `
<ul class="companyinfo">
<li class="list-info">${companyObject.company_type}</li>
<li class="list-info">${companyObject.company_name}</li>
<li class="list-info">${companyObject.company_location}</li>
<li class="list-info">${companyObject.company_phone}</li>
<br>
<li class="list-buttons">
<form action="/activeList" method="POST" class="myform">
<input type="hidden" name="companyId" value="${companyObject.id}">
<input type="submit" value="Active">
</form>
<form action="/deletecompany" method="POST">
<input type="hidden" name="companyId" value="${companyObject.id}">
<input type="submit" value="Delete">
</form>
</li>
<br>
</ul>
`
}
function inactiveList(arrayOfCompanies){
const companyItems = arrayOfCompanies.map(inactiveFiltered).join('');
return `
<div class="list inactive-list">
${companyItems}
</div>
`
}
module.exports = inactiveList;
One function takes an array of companies and then creates an company object. Now here's the latest JQuery attempt, but like I said it hides all the ul elements:
$(document.body).submit(function() {
$('.companyinfo').each(function(i) {
$(this).hide();
})
})
I've been stuck on this for waaay too long and would love any help whatsoever. Thank you!
You are hiding all elements at the same time because the selector .companyinfo returns a list of all elements using the class companyinfo which are all companies in your case. That's why they get hidden all at the same time
One way to achieve your goal is to add ids to the ul elements to be able to address them for each company individually like so: <ul id="companyinfo_${companyObject.company_name}" class="companyinfo">.
Then add a method hideCompany() to replace the $(document.body).submit(function() part:
function hideCompany(companyname) {
$('#companyinfo_' + companyname).hide();
}
Finally, modify <input type="submit" value="Delete">to read <input type="submit" value="Delete" onclick="hideCompany('${companyObject.company_name}')">.

angular2 ngFor won't work

I'm trying to make some textboxes appear everytime a user clicks a button.
i'm doing this with ngFor.
For some reason, the ngFor won't iterate.
I've tried using slice to change the array reference, but still, the text boxes won't appear.
Any idea what i'm doing wrong??
Below are the HTML and component codes.
Thanks!!!
export class semesterComponent {
subjectsNames = [];
addSubject(subjectName: string) {
if (subjectName) {
this.subjectsNames.push(subjectName);
this.subjectsNames.slice();
console.log(subjectName);
console.log(this.subjectsNames);
}
};
<div class="semester-div">
<ul>
<li ngFor="let subject of subjectsNames">
<span>
<input #subjectName type="text" />
<input id = "subjectGrade" type = "number"/>
<input id = "subjectWeight" type = "number"/>
</span>
</li>
</ul>
<br>
<button (click)="addSubject(subjectName.value)">add</button>
<br>
</div>
You are missing the * in *ngFor
<li *ngFor="let subject of subjectsNames">
The way you have your controls written subjectName does not exist because the array is empty and therefore the *ngFor does not render it. Clicking the Add button results in a exception that the value doesn't exist on undefined where undefined is really subjectName.
Moving it outside of the *ngFor will make things work:
<input #subjectName type="text" />
<ul>
<li *ngFor="let subject of subjectsNames">
<span>
{{subject}}
<input id="subjectGrade" type="number"/>
<input id="subjectWeight" type="number"/>
</span>
</li>
</ul>
I suspect you also want to further bind the data as you iterate over the subject names but that's outside the scope of the question.
Here's a plunker: http://plnkr.co/edit/HVS0QkcLw6oaR4dVzt8p?p=preview
First, you are missing * in *ngFor.
Second put out
<input #subjectName type="text" />
from ngFor, should work.

make knockout array object visible based on an id value

All the examples I see are for DOM elements that are explicitly written on the page. In my case I am using the knockout foreach to create a list of items in my observable array:
<div class="tab-pane fade" id="recruiting">
<input type="text" data-bind="value: selectedOrgKey" id="orgSectionId" onchange="FlipOrgView()" style="visibility: hidden;" />
<ul class="list-unstyled" data-bind="foreach: orgs">
<li data-bind="attr: { id: 'orgSection' + orgId}" class="orgSection">
I am currently using a kludgy solution by using the onchange on an hidden element to grab the id and .show() it.
window.OrgDdlUpdated = function () {
$(".orgSection").hide();
var selectedOrgId = $('#orgDropDown').val();
//alert(selectedOrgId);
flipOrgView(selectedOrgId);
};
var flipOrgView = function (id) {
$('#orgSection' + id).show();
};
This technically works, the first time, but as I flip through it all, the selected id lags behind to where it shows the previous selection, not the current one. I know there are various ways to achieve this, so knockout or otherwise, how can i properly toggle the visibility of an array of objects using the knockout foreach method?
how about:
<div class="tab-pane fade" id="recruiting">
<input type="text" data-bind="value: selectedOrgKey" id="orgSectionId" style="visibility: hidden;" />
<ul class="list-unstyled" data-bind="foreach: orgs">
<li data-bind="visible: $parent.selectedOrgKey() === orgId(), attr: { id: 'orgSection' + orgId}" class="orgSection">
im not too sure in your example how you are setting selectedOrgKey but this should do the MVVM behavior i think you are getting at.

how to fetch values of two hidden tags with different id

I have using two anchor tag to transfer the control to same page. and gives two hidden input with same id but different values. as shown in given code.
<li data-icon="false"><a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucher();">
<input type="hidden" id="PRVou" value="payment">PaymentReceipt Voucher</a></li>
<li data-icon="false"><a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucher();">
<input type="hidden" id="PRVou" value="receipt">ReceiptPayment Voucher</a></li>
and i want to get the values of these hidden tags by using following javascript code.
loadAccForPayVoucher = function() {
alert(document.getElementById('PRVou').value);
}
and it always alert payment. how can i get the value according to the link. Thanks.
id attributes are meant to be unique, regardless of their context. There should only be one element in the entire document with a given id.
Give the element a class name instead:
<input type="hidden" class="PRVou" value="payment">
And then use getElementsByClassName:
document.getElementsByClassName('PRVou')[0].value
Try this:
<li data-icon="false"> <a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucher('payment');">
<!--<input type="hidden" id="PRVou" value="payment">PaymentReceipt Voucher</a> --></li>
<li data-icon="false"><a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucher('receipt');">
<!-- <input type="hidden" id="PRVou" value="receipt">ReceiptPayment Voucher</a> --></li>
<script type="text/javascript">
loadAccForPayVoucher = function(type) {
alert(type);
//alert(document.getElementById('PRVou').value);
}
</script>
In HTML the ID attributes are always unique, thus when you call document.getElementById, the DOM of the browser will go out and fetch any (most likely the first) element with the given ID.
What can I do?
Give them separate IDs, your html will look like this:
<li data-icon="false"><a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucherPayment();">
<input type="hidden" id="PRVou-payment" value="payment"/>PaymentReceipt Voucher</a></li>
<li data-icon="false"><a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucherReceipt();">
<input type="hidden" id="PRVou-receipt" value="receipt"/>ReceiptPayment Voucher</a></li>
And then your JavaScript will have separate event handlers:
loadAccForPayVoucherPayment = function() {
alert(document.getElementById('PRVou-payment').value);
}
loadAccForPayVoucherReceipt = function() {
alert(document.getElementById('PRVou-receipt').value);
}
Update: I made you a fiddle :) http://jsfiddle.net/YCXC8/

I am having a few problems trying to create a jquery live search function for basic data set?

I am designing a simple jquery live search function within a widget on a site i'm developing. I have borrowed some code I found and it is working great. The problem is though that instead of using a list like this:
<ul>
<li>Searchable Item 1</li>
<li>Searchable Item 2</li>
etc
I am using a list like this:
<ul>
<li>
<a href="#">
<div class="something>
<img src="something.jpg">
<p>Searchable Item 1</p>
</div>
</a>
</li>
etc.
As you can see the text I want to search is in the p tag. The functions I have used are searching all the other stuff (a href, div, img) and matching text found in those tags as well as the item within the p tag. Sorry if my explanation is a bit confusing but I will show you an example of the code here:
//includes im using
<script type="text/javascript" src="js/jquery-1.7.min.js" ></script>
<script type="text/javascript" src="js/quicksilver.js"></script>
<script type="text/javascript" src="js/jquery.livesearch.js"></script>
//document ready function
$(document).ready(function() {
$('#q').liveUpdate('#share_list').fo…
});
//actual search text input field
<input class="textInput" name="q" id="q" type="text" />
//part of the <ul> that is being searched
<ul id="share_list">
<li>
<a href="#">
<div class="element"><img src="images/social/propellercom_icon.jpg… />
<p>propeller</p>
</div>
</a>
</li>
<li>
<a href="#">
<div class="element"><img src="images/social/diggcom_icon.jpg" />
<p>Digg</p>
</div>
</a>
</li>
<li>
<a href="#">
<div class="element"><img src="images/social/delicios_icon.jpg" />
<p>delicious</p>
</div>
</a>
</li>
</ul>
also here is the jquery.livesearch.js file I am using
jQuery.fn.liveUpdate = function(list){
list = jQuery(list);
if ( list.length ) {
var rows = list.children('li'),
cache = rows.map(function(){
return this.innerHTML.toLowerCase();
});
this
.keyup(filter).keyup()
.parents('form').submit(function(){
return false;
});
}
return this;
function filter(){
var term = jQuery.trim( jQuery(this).val().toLowerCase() ), scores = [];
if ( !term ) {
rows.show();
} else {
rows.hide();
cache.each(function(i){
var score = this.score(term);
if (score > 0) { scores.push([score, i]); }
});
jQuery.each(scores.sort(function(a, b){return b[0] - a[0];}), function(){
jQuery(rows[ this[1] ]).show();
});
}
}
};
I believe the problem lies here:
var rows = list.children('li'),
cache = rows.map(function(){
return this.innerHTML.toLowerCase();
});
it is just using whatever it finds between the li tags as the search term to compare against the string entered into the text input field. The search function actually does work but seems to find too many matches and is not specific as I am also using a quicksilver.js search function that matches terms that are similar according to a score. When I delete all the other stuff from the li list (a href, img, div, etc) the search function works perfectly. If anyone has any solution to this I would be really greatful, I have tried things like:
return this.children('p').innerHTML but it doesn't work, I'm ok with PHP, C++, C# etc but totally useless with javascript and Jquery, they're like foreign languages to me!
In the jquery.livesearch.js file I believe you can replace this line:
var rows = list.children('li'),
with:
var rows = list.children('li').find('p'),
This should make it so the livesearch plugin will only search the paragraph tags in your list.
You will need to change the .show()/.hide() lines to reflect that you are trying to show the parent <li> elements since you are now selecting the child <p> elements:
Change:
rows.show();//1
rows.hide();//2
jQuery(rows[ this[1] ]).show();//3
To:
rows.parents('li:first').show();//1
rows.parents('li:first').hide();//2
jQuery(rows[ this[1] ]).parents('li').show();//3

Categories

Resources