My JS selector for <ul> is not working [duplicate] - javascript

This question already has answers here:
Attaching click event to a JQuery object not yet added to the DOM [duplicate]
(10 answers)
Closed 8 years ago.
I'm using multiple Bootstrap dropdown controls and need to set a value to an input field when a list item of a specific dropdown is selected. For example, say I have 3 dropdowns:
ulSaukContact
ulMoselContact
ulShipContact
All three are running on the server, and I need to get the value of each so I can save them somewhere. So I figured I should probably save the value of each to a hidden input field that I can reference later. Here is my attempted JS code for doing this:
$("#ulSaukContact li a").on("click", function () {
alert('sauk'); // <--- Alert is not shown
var elem = document.getElementById("inpSaukValue");
elem.Value = $(this).text();
});
and the accompanying markup
<div class="dropdown">
<button type="button" class="btn btn-default dropdown-toggle" id="btnSaukList" data-toggle="dropdown" runat="server"
style="width: 100%;">
<span style="padding-right: 250px;">Select a Saukville contact</span>
<span class="caret"></span>
</button>
<ul id="ulSaukContact" class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1" runat="server" style="width: 100%">
<!--NOTE: Intentionally left blank; li's are generated by code behind to populate users from Sharepoint.-->
</ul>
<input id="inpSaukValue" type="hidden" />
</div>
When I run the app and select a value in the Saukville dropdown, no alert is displayed. Note that the li's and a's within the ul is created on Form_Load so they can be populated with data. I think my selector is wrong. I cleared out my cached files in Chrome (which caused issues before) and I still do not see the alert.
Any advice appreciated (thanks for all the recent JS/BS/JQ advice)...

Because the elements don't exist at the time you're attempting to bind events to them, you need to delegate events to the containing element with on:
$("#ulSaukContact").on("click", "li a", function () {
...

Related

Drop down menu items behavior

Hi I'm working on a MVC application that has a drop down menu in it, and the items
in this drop down are fetched from the DB via a foreach.
foreach (Category item in Model.CategoriesV){
<input type="submit" class="dropdown-item" id="Show"
value="#item.CategoriesName" name="CategName" />
}
I get 3 results from this for each (Mobiles-Consoles-Tablets),
I have another div that contains an image gallery.
I used this code to hide this gallery once I click on an item in the drop down menu.
Here's the image galley(I put it in a Partial View)
<div id="ImageGalleryDiv">
#Html.Partial("_ImageGallery", Model)
</div>
And here's the script that I used to hide the gallery once I click on drop down items list.
<script>
$(document).ready(function () {
$('#Show').click(function () {
$('#ImageGalleryDiv').hide("100");
});
});
Everything is working fine when I click on Mobiles (the first item in the drop down),the others items aren't working.
Any help would be appreciated.
id should be unique. That is it's purpose. Uniquely identifying an element. You are not allowed to use duplicate id's on a page. It can result in unwanted behavior like you are experiencing now. Basically, jQuery gets the first element that it finds with the id and then ignores all the other. Also in plain javaScript we not not have a getElementsById method but getElementById.
Read more about it here -> Why are duplicate ids not allowed in HTML
So you can use a class instead.
Also, class and id should be lowercase and dash separated string-string ( if the consist of multiple words ) , not camelCase.
See example below
const categories = ['Mobiles', 'Consoles', 'Tablets']
categories.forEach(categ => {
const input = `<input type="submit" class="dropdown-item show" id="show-${categ}" value=${categ} name=${categ} />`
$('#categories').append(input);
});
$('.show').click(function() {
$('#image-gallery-div').hide("100");
});
#image-gallery-div {
height: 100px;
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="categories">
</div>
<div id="image-gallery-div">
</div>

External function not working on page load, but working on button press

I have an EJS template where I am using an external function in 2 different ways. When the document loads, I want to loop through existing data, and on button click I want to fire the function as well. Its working well on click, but not working when page loads.
The external JS function inserts a form for clients to declare their debts. The users have already declared their debts. I'm working on the edit page where they can change previous information or declare new debts.
When the page loads I want to:
A) loop through their existing debts, feed the information into the addDebt function and create a prepopulated form on the fly.
B) I also want them to be able to add new debts with the dropdown button that use the same function to insert a blank form.
B works perfectly, but the function isn't recognised in A. I'm sure this is a timing issue, with the DOM content not having been loaded when NODE tries to render A. I just can't figure out how to fix it. When I try adding window.onload to function.js it stops working altogether!
Sorry if this question is verbose or unclear, as my username suggests I'm new to this.
function.js
function addDebt(x, y) {
DOM manipulation to insert different form elements based on value of x (ie “credit card”,
“home Loan” etc)
if (y == '1')
generate pre populated fields for existing debts
Ejs
<div class="container main">
<h4>Edit debts:</h4>
//PART A - loop through existing debts of the user and feed them into the
function to generate pre populated forms for editing the information
<% liabilities.forEach(function(liability){ %>
addDebt(<%= liability.type %>, ‘1’);
<% }); %>
// PART B - allow user to add new debts by selecting them from dropdown
<div class="dropdown col-12 col-sm-3 mb-2">
<button data-toggle="dropdown">
Add a new debt
</button>
<div class="dropdown-menu">
<a class="dropdown-item" onclick="addDebt('Home Mortgage', '0')"
href="#">Mortgage on your home</a>
<a class="dropdown-item" onclick="addDebt('Credit Card, '0',
'0')"href="#">Credit cards</a>
<a class="dropdown-item" onclick="addDebt('Car Loan', '0')"
href="#">Car Loans</a>
</div>
</div>

Get li value from ul filled by JavaScript [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I have filled some "ul"s directly in HTML e.g.
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Kennzahl
<span class="caret"></span></button>
<ul class="dropdown-menu" id="measure">
<li>volume</li>
<li>netSentiment</li>
<li>authors</li>
</ul>
and had no trouble reading the selected value by
$('#measure li').on('click', function(){
$(this).text();
});
Then I have tried to get the chosen Value from a "ul" that I filled by JavaScript:
Something like
$('#projectId').append('<li>' + projects[i].name + '</li>');
The Select is filled with the "li"s. But when I select one, the result isn't caught by the same JavaScript I could use with the "li" directly filled in HTML.
When you dynamically add new elements after the page has loaded, you need to delegate the events to a parent element. You've almost done this, just change you code to
$('#measure').on('click','li', function(){
$(this).text();
});
Note your method here will not do anything - but ive kept the code as close to your example. Perhaps you meant console.log($(this).text());
What you need is Binding for dynamically created elements
$('#measure').on('click', 'li', function(){
alert($(this).text());
});
$('#measure').append('<li>abc</li>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="caret"></span></button>
<ul class="dropdown-menu" id="measure">
<li>volume</li>
<li>netSentiment</li>
<li>authors</li>
</ul>
Here i have created abc li using jquery but still on clicking it, it gives alert just like other li.

Change the text in a button using javascript? [duplicate]

This question already has answers here:
How do I change the text of a span element using JavaScript?
(18 answers)
Closed 6 years ago.
I have a FAQ list that works that way : there are several mini cards that contain a question (some text) and a button (let's say "see the answer"). When I click on the button, the answer to the question appears above the button. Then the button should not be a "see the answer" button, but a "close" one. I need a little help with that last part.
Here is what I have done :
<p>Question</p>
<div class="collapse" id="FAQ">
<div class="well">
Answer to the question
</div>
</div>
<a class="btn" role="button" data-toggle="collapse" href="FAQ" aria-expanded="false" aria-controls="collapseExample">See the answer</a>
Side question : since this is a list and I'm going to have several "See the answer/Close" buttons, I would say I'm not allowed to use an id to make it work, am I ?
You can dynamically set the text on the button by $(".btn").innerHTML = "new text to be displayed". Put this in your first click(function() {...}) function.
And no, never use the same id for multiple elements. Use classes instead. You can have multiple classes on one element. So for example you may have class="btn close" and then use toggleClass("close") to add it when it's not there, remove it when it is.

How to pass viewBag data into Javascript and display in div

I am always leery of asking dumb questions here but I need to move on and create a few more active pages but this is a lingering issue in my way ...The chtml in razor contains a switch ,,, in one of the cases there's three if statements.. THIS IS JUST ONE OF THEM depending on the if statements a different string in viewdata is to be fed into a div and the div class "hidden" is removed and the supplied text displayed....
I have over the past few hours regained my briefly lost ability to remove that hidden class (I hate css) but I have never been able to update the content of the div.
PLEASE Advise Thank you !!
<div id="divUnUsableEvent" class="hidden">
<div class="row clearfix">
<div class="col-md-1"></div>
<div id="systemExceptionLbl" style="font-size: 2em; color: red;"
class="text-danger:focus">
Please contact IS support
</div>
</div>
</div>
//alphascores Not present AND BetaSCores Not Present Ready for xxxxx //alphascores Not present AND BetaSCores Not Present Ready for xxxxx Scoring
if (!Convert.ToBoolean(#ViewData["alphaPresent"])
&& !Convert.ToBoolean(#ViewData["betaPresent"]))
{
<script type="text/javascript">
$(function() {
$('#UnUseableEvent').addClass("hidden");
var txtMsg = #Html.Raw(Json.Encode(ViewData["beforeAlpha"]));
$('#divUnUsableEvent').removeClass("hidden");
$('#systemExceptionLbl').removeClass("hidden");
$('#systemExceptionLbl').innerText = txtMsg;
});
</script>
<a id="XXXReScoreEvent"
href="#Url.Action("Readyforxxxxxx", "Exception", new { Id = (int)#ViewData["Id"] })"
class="btn btn-primary btn-default btn-too-large pull-left margin"
aria-label="XXXReScoreEvent">
<span class="glyphicon glyphicon-edit" aria-hidden="true"></span> Ready for xxxxxx Scoring
</a>
}
break;
I know its hitting the javascript, as that html element (a button) named '#UnUseableEvent' is correctly being hidden in this case. I of course would want the javascript out of this html page and just have function calls in the razor but baby steps
Specifically regarding the ('#systemExceptionLbl').innerText = txtMsg; I have tried
.text
.value
.innerHTML
all to no avail. I can see the correctly formatted Json.Encoded text reach the variable txtMsg, but again I cant get it into the div ..
I am having success now with displaying the div (remove class hidden) I was attempting to affect the wrong div name and the line removing the hidden class from the element $('#systemExceptionLbl') is not needed.
I even tried to skip the JQuery reference and go old school document.getElementById('systemExceptionLbl').innerHTML = txtMsg;
Ever tried :
$('#systemExceptionLbl').text( txtMsg );
or
$('#systemExceptionLbl').html( txtMsg );
as innerText is not a jquery function. Instead use .html() or .text() to insert data into it

Categories

Resources