Wrong result after compare select.val() and span.text() - javascript

I have a folowing problem.
On click button Filter I want get entries with selected city.
SO forbid me write big code, so I show only div with data. I think you can add select with options, if you want.
(Select id = "cityFilter" , options: Dnepr, Kharkiv, Lviv)
HTML:
<div id="data">
<div>
<a class="userEmail" href="#">user1#domain.ua </a>
<span> user1 </span>
<span> Dnepr </span>
<span><input type = "button" value = "x" /></span>
</div>
<div>
<a class="userEmail" href="#">user2#domain.ua </a>
<span> user2 </span>
<span> Kharkiv </span>
<span><input type = "button" value = "x" /></span>
</div>
<div>
<a class="userEmail" href="#"> user3#domain.ua </a>
<span> user3 </span>
<span> Lviv </span>
<span><input type = "button" value = "x" /></span>
</div>
<div>
<a class="userEmail" href="#"> user4#domain.ua </a>
<span> user4 </span>
<span> Dnepr </span>
<span><input type = "button" value = "x" /></span>
</div>
<div>
<a class="userEmail" href="#"> user5#domain.ua </a>
<span> user5 </span>
<span> Lviv </span>
<span><input type = "button" value = "x" /></span>
</div>
</div>
cityFilter.js (The description of the code in comments):
$(function() {
//click on button
$('body > input').on('click', function() {
//get selected value
var cityFilter = $('#cityFilter').val();
//sort out spans which contains city names
$('#data > div > a + span + span').each(function() {
//for check the received value
console.log($(this).text());
//compare selected value and span text
if ($(this).text() != cityFilter) {
console.log('true');
}
});
});
});
I got all true. Where is the problem ?

your spans have leading and trailing spaces
i.e. " abc " != "abc"
try the following instead:
if ($(this).text().trim() != cityFilter) {
console.log('true');
}

Related

How to display a show/hide content based on image change in if/else javascript

I am having a if / else statement that display a div containing images. There are two images, Image 1 & Image 2.
And a dropdown of two selections. by choosing one option value and first image the condition logic working fine.
Query:
when change to second image and choosing the option value how to make the condition work and display a different div
HTML
<p class="text-center accuracy">
<span id="img-left" class="arrow" onclick=larrow();>
<i class="fas fa-angle-left"></i></span>
<span id="changer-txt" class="accuracy changedtext">Image 1</span>
<span id="img-right" name="cat" class="arrow" onclick=rarrow();>
<i class="fas fa-angle-right"></i></span> <br /> <span> </span>
</p>
JS
if ($('#dropdown').val() == 'Timeseries' && $('#changer-txt').val() == 'Image 2') {
$('#time_black_low').show();
}
changer-txt statement is not true and condition not working.
You have to use $('#changer-txt').text() instead of $('#changer-txt').val()
HTML
<p class="text-center accuracy">
<span id="img-left" class="arrow" onclick=larrow();>
<i class="fas fa-angle-left"></i></span>
<span id="changer-txt" class="accuracy changedtext">Image 1</span>
<span id="img-right" name="cat" class="arrow" onclick=rarrow();>
<i class="fas fa-angle-right"></i></span> <br /> <span> </span>
</p>
JS
if ($('#dropdown').val() == 'Timeseries' && $('#changer-txt').text() == 'Image 2') {
$('#time_black_low').show();
}
I have made some changes to your code.
Changes are marked as either <!-- CHANGE HERE:... --> in HTML code and // CHANGE HERE: ... in JS code:
// CHANGE HERE: show default values properly
$('#output').hide();
$('#second-output').hide();
$('#model1').show();
$('#model1-div').show();
function larrow() {
document.getElementById('changer-txt').innerHTML = "Image 1";
}
function rarrow() {
document.getElementById('changer-txt').innerHTML = "Image 2";
}
$('#dropdown').on('change', function() {
switch (this.value) {
case 'model1':
$('.model1').show();
$('.model2').hide();
break;
case 'model2':
$('.model2').show();
$('.model1').hide();
break;
default:
}
});
$('#go').on('click', function() {
//console.log($('#changer-txt').html(), $('#dropdown').val(), $('#sub').val());
//console.log($('#changer-txt').html() == "Image 2", $('#dropdown').val() == "model1", $('#sub').val() == "submodel1");
// CHANGE HERE: simplify the checks
if ($('#dropdown').val() == 'model1' && $('#sub').val() == 'submodel1') {
// CHANGE HERE: use html() instead of val() to access innerHTML
if ($('#changer-txt').html() == 'Image 2') {
$('#second-output').show();
$('#output').hide();
} else {
$('#output').show();
$('#second-output').hide();
}
}
});
.model1,
.model2,
#output #second_output {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<p> Select Model</p>
<select id="dropdown">
<option value="model1">Model 1</option>
<option value="model2">Model 2</option>
</select>
<div id="model1" class="model1">
<p class="text-center accuracy">
<span id="img-left" class="arrow" onclick=larrow();><</span>
<!-- CHANGE HERE: move &nbsp outside changer-txt -->
<span> </span>
<span id="changer-txt" class="accuracy changedtext">Image 1</span>
<span> </span>
<span id="img-right" class="arrow" onclick=rarrow();> > </span>
<br>
<span> </span>
</p>
</div>
<!-- CHANGE HERE: id should be unique -->
<div id="model1-div" class="model1"> Model 1 Working !!! </div>
<div class="model2"> Model 2 Working !!! </div>
</section>
<br><br><br>
<section>
<select id="sub">
<option value="submodel1" selected>Sub Model 1 </option>
<option value="submodel2">Sub Model 2</option>
</select>
<button id="go" type="button" class="btn btn-blue btn-lg">Launch </button>
</section>
<div id="output">
<p> Final Output !! </p>
</div>
<!-- CHANGE HERE: replaced underscore with hyphen in id (optional) -->
<div id="second-output">
<p> Output 2nd Image Final Output !! </p>
</div>

add 'ids' to checkbox elems from ~ sibling element innerText val

Goal: I am trying to iterate through a series of checkboxes, and add an "id" to each elem with the value of the checkboxes sibling text value. i.e. inner text of .k-in
Recent attempt:
function addSelectors() {
const checks = document.querySelectorAll('.k-treeview-lines input[type="checkbox"]');
[].forEach.call(checks, function (checks) {
let knn = document.querySelectorAll('.k-treeview-lines input[type="checkbox"] ~ .k-in');
checks.id = knn.innerText;
});
}
HTML is a series of the below:
<div class="k-mid">
<span class="k-checkbox-wrapper" role="presentation">
<input type="checkbox" tabindex="-1" id="undefined"
class="k-checkbox"><-- id here
<span class="k-checkbox-label checkbox-span"></span>
</span>
<span class="k-in">I want this</span><---- this text
</div>
Do not want to load jQuery...
function addSelectors() {
const checks = document.querySelectorAll(
'.k-treeview-lines input[type="checkbox"]'
);
checks.forEach(function (checkbox) {
const textVal = checkbox.parentElement.nextElementSibling.innerText;
checkbox.setAttribute("id", textVal);
});
}
addSelectors();
<div class="k-treeview-lines">
<div class="k-mid">
<span class="k-checkbox-wrapper" role="presentation">
<input
type="checkbox"
tabindex="-1"
id="undefined"
class="k-checkbox"
/>
<span class="k-checkbox-label checkbox-span"></span>
</span>
<span class="k-in">tempID</span>
</div>
</div>
The item you are requesting is not actually the sibling, they don't share the same parent.
You could do something like this:
function addSelectors() {
const checks = document.querySelectorAll('input[type="checkbox"]');
checks.forEach(c => {
c.id = c.parentNode.nextElementSibling.innerText;
});
}
addSelectors();
<div class="k-mid">
<span class="k-checkbox-wrapper" role="presentation">
<input type="checkbox" tabindex="-1" id="undefined" class="k-checkbox">
<span class="k-checkbox-label checkbox-span"></span>
</span>
<span class="k-in">I want this</span>
</div>

Dropdown menu click eventListener producing a different target element based on area clicked

I have a MaterializeCSS dropdown menu implemented with this HTML. The event listener works only if the dropdown item is clicked in the upper portion.
<div class="left">
<span id="notificationTotal" class="new badge red" style="display:none">
</span>
<a class="dropdown-trigger" href="#!" data-target="notificationsDropdown">
<i class="material-icons"> message</i>
</a>
</div>
<ul id="notificationsDropdown" class="dropdown-content">
</ul>
I'm using the following Javascript to populate the menu with notifications. This is working just fine.
// Reset Notification Dropdown
notificationsDropdown.innerHTML = '';
notifications.forEach(notif => {
const displayTime = moment(notif.date).fromNow();
let typeIcon = 'sms';
if (notif.type === 'chat') {
typeIcon = 'lock';
}
notificationsDropdown.innerHTML += `<li class="notification">
<a style="margin-top:0px;margin-bottom:0px;padding-bottom: 0;font-size:14px" href="#" class="blue-text">
<span class="js-patientName">
${notif.contact.firstName} ${notif.contact.lastName}</span>
<span class="js-notificationPhone" style="display:none">${
notif.contact.phone
}</span>
<span class="js-patientId" style="display:none">${
notif.patientId
}</span>
<span class="js-patientDOB" style="display:none">${
notif.contact.birthDate
}</span>
<p style="margin-top:0px;margin-bottom:0px;padding-bottom: 0;padding-top: 0;">
<i style="display: inline-flex; vertical-align:middle" class="tiny material-icons">${typeIcon}</i>
<span class="black-text" style="font-size:12px">
${displayTime}
</span>
</p>
</a></li>`;
});
notificationsDropdown.innerHTML += `<li class="divider" class="blue-text"></li><li>See All Notifications</li>`;
}
The dropdown gets populated and when a user clicks on a particular dropdown .li entry depending on the exact location they click, it may or not work. The user must click at the main top of the dropdown item.
This is the event listener code that extracts the values from the hidden span elements.
document
.querySelectorAll('#notificationsDropdown', '.li .a .notification')
.forEach(input =>
input.addEventListener('click', async e => {
// console.log('clicked', e.target);
console.log(e.target.parentNode);
const name = e.target.children[0].textContent.trim();
const phone = e.target.children[1].textContent.trim();
const patientId = e.target.children[2].textContent.trim();
const birthDate = e.target.children[3].textContent.trim();
console.log('patientid ', patientId);
const patient = {
name,
patientId,
phone,
birthDate
};
Is there a way I can rewrite the eventListener code to resolve this issue? Possibly instead of using e.target.children[insert_number_here].textContent I could use .closest('js-patientId') or similar ?
This is how the HTML is rendered to the page. This is an example of a single notification:
<ul
id="notificationsDropdown"
class="dropdown-content"
tabindex="0"
style="display: block; width: 177.297px; left: 1648.7px; top: 0px; height: 251px; transform-origin: 100% 0px; opacity: 1; transform: scaleX(1) scaleY(1);"
>
<li class="notification">
<a
style="margin-top:0px;margin-bottom:0px;padding-bottom: 0;font-size:14px"
href="#"
class="blue-text"
>
<span class="js-patientName">ANDREW TAYLOR</span>
<span class="js-notificationPhone" style="display:none">
5555551212
</span>
<span class="js-patientId" style="display:none">
1
</span>
<span class="js-patientDOB" style="display:none">
1960-01-01
</span>
<p style="margin-top:0px;margin-bottom:0px;padding-bottom: 0;padding-top: 0;">
<i
style="display: inline-flex; vertical-align:middle"
class="tiny material-icons"
>
sms
</i>
<span class="black-text" style="font-size:12px">
2 hours ago
</span>
</p>
</a>
</li>
<li class="divider" />
<li>
<a href="/notifications" class="blue-text">
See All Notifications
</a>
</li>
</ul>;
For dropdowns, the better way to handle actions is through onChange event. So you could attach your eventHandler on onChange of dropDown itself rather than attaching onClick on each of dropDown items. So whenever you change the selected value the onChange event will be triggered and you can easily get the selected value.
I was able to remove the in each li. Then adjust the value assignment to use the following:
e.target.parentNode.children[0].textContent.trim();

Can find input field with JQuery

I have a method ForceNumeric that i want to apply to a input field. What i want is this: template_item_input[0].ForceNumeric();
My renderd HTML looks like this:
<div id="itemList">
<div class="ingress"></div>
<div id="itemListItem[0]" class="dataListItem first">
<span class="put-left startTimeSpan"></span>
<span class="put-left separator"></span>
<span class="put-left endTimeSpan"></span>
<span class="put-left ruleSpan"></span>
<span class="put-left valueItem">
<input id="template_item_input[0]_value_item" class="styledInput">
</span>
<span class="put-left unit"></span>
</div>
<div id="itemListItem[1]" class="dataListItem first">
<span class="put-left startTimeSpan"></span>
<span class="put-left separator"></span>
<span class="put-left endTimeSpan"></span>
<span class="put-left ruleSpan"></span>
<span class="put-left valueItem">
<input id="template_item_input[1]_value_item" class="styledInput">
</span>
<span class="put-left unit"></span>
</div>
</div>
In $( document ).readyi'm doing this. this.id is equal to template_item_input[0] but value is a empty object object[]
$("#carbList").children(".carbListItem").each(function () {
var value = $(this.id).find('.put-left.valueItem');
var inp = $(value).find('input');
$(inp).ForceNumericOnly();
}),
What am i doing wrong?
this.id will return id of the clicked element. Use $(this) or $('#'+this.id) instead of $(this.id).
$(#YOUR_ID) is a valid selector for to get element having id as YOUR_ID. $(YOUR_ID) will return elements having tag as YOUR_ID => <YOUR_ID>
You do not need to wrap value in jQuery wrapper. It is already $ wrapped object.

How to get id of anchor tag, regardless of where it is in hierarchy?

I want to get the id/class/both of the anchor tag, regardless of where it falls in the tag hierarchy. Example below is strange but realistic for my purposes because our website is accessed through a CMS that I have no control over. If people add multiple levels of formatting at different times, the CMS likes to add new span's...
So, having the live with the above facts, I want to pin down specific anchor tags by their id/class/both, but I don't always know where they will be located in the tag drill-down.
<div id="div_id_A" class="div_class_A">
<div class="div_class_A">
<a href="#" id="anchor_id_A" class="anchor_class_A">
<span class="span_class_A">
<span id="span_id_B">
<span id="span_id_C" class="span_class_C">
<p>
Click Me
</p>
</span>
</span>
</span>
</a>
</div>
</div>
I have started off like such,
var dataLayer = dataLayer || [];
document.addEventListener('click', function(event) {
var telm = event.target.parentNode.className;
var delm = 'anchor_id_A';
console.log(telm);
if (telm == delm) {
dataLayer.push({
'youClicked': telm
});
console.log(dataLayer);
};
});
*WHERE: telm = target element; delm = desired element.
To clarify. I am specifying anchor for a reason, it is not simply for the example. As I am restricted by our CMS, I can't go in and add markup to pre-defined code (i.e. template), but I do need to know what link was clicked as exactly as possible (for Google Analytics), so that I can track down what users are ignoring, not seeing, or prefering.
You can navigate up the hierarchy until you reach the anchor element, then just read its ID.
See here:
var dataLayer = dataLayer || [];
document.addEventListener('click', function(event) {
var el = event.target;
while (el.parentElement && el.tagName != 'A') {
el = el.parentElement;
}
dataLayer.push({
'youClicked': el
});
console.log(dataLayer);
alert(el.id);
});
<div id="div_id_A" class="div_class_A">
<div class="div_class_A">
<a href="#" id="anchor_id_A" class="anchor_class_A">
<span class="span_class_A">
<span id="span_id_B">
<span id="span_id_C" class="span_class_C">
<p>Click Me</p>
</span>
</span>
</span>
</a>
</div>
</div>
What you're trying to achieve, is probably something like this :
var dataLayer = [];
document.addEventListener('click', function(event) {
var needle = 'anchor_class_A'; // The class of the element you're looking for
var closest = event.target.closest("." + needle);
if(closest && closest.id) {
dataLayer.push({
'youClicked': closest.id
});
alert(JSON.stringify(dataLayer, null, '\t'));
}
});
<div id="div_id_A" class="div_class_A">
<div class="div_class_A">
<a href="#" id="anchor_id_A" class="anchor_class_A">
<span class="span_class_A">
<span id="span_id_B">
<span id="span_id_C" class="span_class_C">
<p class="clicker">
Click Me
</p>
</span>
</span>
</span>
</a>
</div>
<div class="div_class_A">
<a href="#" id="anchor_id_X" class="anchor_class_A">
<span class="span_class_A">
<span id="span_id_Y">
<span id="span_id_Z" class="span_class_C">
<p class="clicker">
Click Me
</p>
</span>
</span>
</span>
</a>
</div>
</div>

Categories

Resources