Content for second div is not being alerted using $(this) - javascript

This is my full code:
<input id="storecipient">
<div class="hidbdsp">
<div class="hidname">tomato</div>
<div class="hidname">orange</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#storecipient").on('input', function() {
var thisFstchar = $(this).val();
var name = $(this).siblings(".hidbdsp").children(".hidname").html();
if (thisFstchar.charAt(0) == name.charAt(0)) {
alert(name);
}
});
});
</script>
What my js code does is alerts the full word that contains the first letter of the word typed on the input. So when the letter "t" is typed, the word "tomato" shows up, but when "o" is typed on the input, "orange" does not show up. Even though both "orange" and "tomato" have the same class ".hidname", the $(this) selector only will select tomato but skips over orange. Why is this?

Try this
$(document).ready(function() {
$("#storecipient").on('input', function() {
var thisFstchar = $(this).val();
$(this).siblings(".hidbdsp").children(".hidname").each(function() {
var name = $(this).html();
if (thisFstchar.charAt(0) == name.charAt(0)) {
alert(name);
}
});
});
});
<input id="storecipient">
<div class="hidbdsp">
<div class="hidname">tomato</div>
<div class="hidname">orange</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

As #misner3456 stated, jQuery.html() returns the HTML of the first matched element only. To get the HTML for all of the matched elements, try something like looping over all of the classes and appending each element's HTML to a string. For example:
let html;
$(".hidname").each(function() {
html += $(this).html();
});

You can refactor to directly iterate $(".hidbdsp .hidname").each() rather than finding the sibling.
$(document).ready(function() {
$("#storecipient").on('keyup', function() {
var thisFstchar = $(this).val();
$(".hidbdsp .hidname").each(function() {
var name = $(this).html();
if (thisFstchar.charAt(0) == name.charAt(0)) {
alert(name);
}
});
});
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<input id="storecipient">
<div class="hidbdsp">
<div class="hidname">tomato</div>
<div class="hidname">orange</div>
</div>

To get all children and descendant:
$('.hidbdsp *')
To get only direct children:
$('.hidbdsp > *')
.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input id="storecipient">
<div class="hidbdsp">
<div class="hidname">tomato</div>
<div class="hidname">orange</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#storecipient").on('input', function() {
var thisFstchar = $(this).val();
$('.hidbdsp *').each(function() {
var name = $(this).html();
if (thisFstchar.charAt(0) == name.charAt(0)) {
alert(name);
}
});
});
});
</script>
</body>
</html>

Related

Remove <li> element from <ul> onclick without refreshing page

At the moment i need to remove an li element created by jQuery when it has been clicked.
(function() {
$(document).ready(function() {
$("#likeform").submit(function(event) {
var input = $(this).children("input[name='thing']")
var thing = $(input).val()
$("#likes").append("<li>" + thing + "</li>")
$(input).val("")
event.preventDefault()
})
})
var li = $('<li/>')
.onclick(function() {
$(this).remove()
})
}())
var listitems = document.getElementsByTagName("li")
for (var i = 0; i < listitems.length; i++) {
listitems[i].onclick = this.parentNode.removeChild((this))
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>My New Pen!</title>
<link rel="stylesheet" href="styles/index.processed.css">
</head>
<body>
<h1>What do you like?</h1>
<form id=likeform>
<input name=thing placeholder="a thing you like" size=30>
<input type=submit>
</form>
<ul id=likes></ul>
<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="scripts/index.js"></script>
</body>
</html>
Currently this has been successful apart from i need to manually reload the page for the change to take effect
Your problem is right here:
var li = $('<li/>').onclick(function() {
$(this).remove()
});
First of all you don't need the comparison operators (<, >) as JQuery will select elements by their tag names. Also, you can't add event listeners the "normal" way on dynamically created elements.
This is discussed right here.
To fix your problem replace the above with this:
$(document).on("click", "li", function() {
$(this).remove();
});
Working example:
(function() {
$(document).ready(function() {
$("#likeform").submit(function(event) {
var input = $(this).children("input[name='thing']")
var thing = $(input).val()
$("#likes").append("<li>" + thing + "</li>")
$(input).val("")
event.preventDefault()
})
})
var li = $(document).on("click", "li", function() {
$(this).remove();
});
}())
var listitems = document.getElementsByTagName("li")
for (var i = 0; i < listitems.length; i++) {
listitems[i].onclick = this.parentNode.removeChild((this))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>What do you like?</h1>
<form id=likeform>
<input name=thing placeholder="a thing you like" size=30>
<input type=submit>
</form>
<ul id=likes></ul>
I think this is essentially what you are trying to do:
$('li').each(function (i) {
$(this).click(() => $(this).remove());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<ul>
<li>foo</li>
<li>bar</li>
</ul>
</body>
would you please try following.
(function() {
$(document).ready(function() {
$("#likeform").submit(function(event) {
var input = $(this).children("input[name='thing']")
var thing = $(input).val()
$("#likes").append("<li>" + thing + "</li>")
$(input).val("")
event.preventDefault()
})
})
}())
var listitems = document.getElementsByTagName("li")
for (var i = 0; i < listitems.length; i++) {
listitems[i].onclick = this.parentNode.removeChild((this))
}
$(document).on("click", "#likes li", function(){
$(this).remove();
});

Select word next to symbol

I have jquery code on keypress 35 which is # to dropdown div. I need to get the word that is standing next to # e.g.
<textarea></textarea> And I type #Michael I want to store #Michael in var name
After making an ajax request to check if Michael exists in the database and if it does, echo it inside dropdown div. After what I click on some from the list and replace it with name and # before name like if I got result:
Michael Parker and click on this one to replace this one with name value.
I need to select word that is typed with #
[Q] how to select the word that is standing next to #?
Try this:
function getName(){
var t = document.getElementsByTagName('textarea')[0].value;
var name = t.split(' ');
name.forEach(function(str){
if(str[0] === '#') {
return str;
}
});
}
I used this for test
<textarea>asjdaksdjans #hacj asdasd</textarea>
<button onclick="getName()">find</button>
I hope this is what you wanted.
EDIT
function getName(){
var t = document.getElementsByTagName('textarea')[0].value;
if(t[t.length-1]=== ' '){
var name = t.split(' ');
name.forEach(function(str){
if(str[0] === '#') {
console.log(str);
}
});
}
}
For test:
<textarea onkeyup="getName()">asjdaksdjans #hacj asdasd</textarea>
EDIT
jQuery(function($){
$('textarea').on('keyup', function(event){
var text = $(this).val();
if(text[text.length-1]=== ' ') {
var name = text.split(' ');
$.each(name, function(i, str) {
console.log(i, str);
if(str[0] === "#") {
alert('name is:' +str);
}
});
}
});
});
This is working example. Note that you cannot 'getvalue' from event handler. But you can call action from that handler.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var capName = '';
var capStart = false;
$('#txt').keypress(function (e) {
if (e.key == '#') {
capStart = true;
capName = '';
}
if (capStart && /[a-z0-9_#-]/i.test(e.key)) {
capName += e.key;
}
if (capStart && !/[a-z0-9_#-]/i.test(e.key)) {
capStart = false;
doSomething(capName);
}
});
function doSomething(text) {
$('#result').html(capName);
}
});
</script>
</head>
<body>
<textarea id="txt"></textarea><br />
<div id="result"></div>
</body>
</html>

Why this function javascript not alert?

Why this function javascript not alert ?
First , Click CLICK 1 it's will show delete and then click delete
Why not alert 111-aaaa How can i do that?
https://jsfiddle.net/tdpusq05/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div onclick="test_fn1()">CLICK 1</div>
<div id="demo"></div>
<script>
function test_fn1() {
document.getElementById("demo").innerHTML = "<span onclick='delete_fn('111-aaaa')'>delete</span>";
};
</script>
<script>
function delete_fn(no_delete)
{
alert(no_delete);
};
</script>
Remove single quotes from onclick around delete_fn('111-aaaa') like following
function test_fn1() {
document.getElementById("demo").innerHTML = "<span onclick=delete_fn('111-aaaa')>delete</span>";
};
<html>
<head>
</head>
<body>
<div onclick="test_fn1()">CLICK 1</div>
<div id="demo"></div>
<script>
function test_fn1() {
document.getElementById("demo").innerHTML = "<span onclick='delete_fn(\"111-aaaa\")'>delete</span>";
}
</script>
<script>
function delete_fn(no_delete) {
alert(no_delete);
};
</script>
</body>
</html>
change the test_fn1 method to escape the quotes, here is the fiddle
function test_fn1() {
document.getElementById("demo").innerHTML = "<span onclick=\"delete_fn('111-aaaa')\">delete</span>";
}
function delete_fn(no_delete)
{
alert(no_delete);
}
JS will not catch dynamically created elements by using onclick function.
you have to do event delegation (if you are using jQuery) :-
$('#id').on('click', 'yourSelector', function() {
//do something
});

Json Object to HTML table

I have a simple page with a "button/link" when i press the button i need to call the github api to return all issues logged in my repository and show in table format.
But when i hit the link nothing happends..
<html>
<head>
<script src="json-to-table.js"></script>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="script.js"></script>
<script src="script.responsive.js"></script>
</head>
<body>
<h2>All Issues</h2>
VIEW
<div id="ghapidata" class="clearfix">
<script type="text/javascript">
$(function() {
$('#ghsubmitbtn').on('click', function(e) {
e.preventDefault();
$('#ghapidata').html('<div id="loader"><img src="css/loader.gif" alt="loader..."></div>');
var ghissues = 'https://api.github.com/repos/stroes/stroestest/issues';
requestJson(ghissues, function(json) {
if(json.message == "Not Found") {
$('#ghapidata').html("<h2>No Issues found in this repository</h2>");
}
else {
var jsonHtmlTable = ConvertJsonToTable(ghissues, 'jsonTable', null, 'Download');
}
}
}
});
</script>
</div>
</body>
</html>
Can anyone point me to where i have gone wrong with my code
your script is inside your div tag. When you change the html inside it, whole script will be removed. Try to place the script outside the div tag.
<html>
<head>
<script src="json-to-table.js"></script>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="script.js"></script>
<script src="script.responsive.js"></script>
</head>
<body>
<h2>All Issues</h2>
VIEW
<div id="ghapidata" class="clearfix"></div>
<script type="text/javascript">
$(function() {
$('#ghsubmitbtn').on('click', function(e) {
e.preventDefault();
$('#ghapidata').html('<div id="loader"><img src="css/loader.gif" alt="loader..."></div>');
var ghissues = 'https://api.github.com/repos/stroes/stroestest/issues';
requestJson(ghissues, function(json) {
if(json.message == "Not Found") {
$('#ghapidata').html("<h2>No Issues found in this repository</h2>");
}
else {
var jsonHtmlTable = ConvertJsonToTable(ghissues, 'jsonTable', null, 'Download');
}
}
}
});
You should see errors in your console. You didn't close the functions right
$(function () {
$('#ghsubmitbtn').on('click', function (e) {
e.preventDefault();
$('#ghapidata').html('<div id="loader"><img src="css/loader.gif" alt="loader..."></div>');
var ghissues = 'https://api.github.com/repos/stroes/stroestest/issues';
requestJson(ghissues, function (json) {
if (json.message == "Not Found") {
$('#ghapidata').html("<h2>No Issues found in this repository</h2>");
} else {
var jsonHtmlTable = ConvertJsonToTable(ghissues, 'jsonTable', null, 'Download');
}
});
});
});
please look here again
var jsonHtmlTable = ConvertJsonToTable(ghissues, 'jsonTable', null, 'Download');
The second parameter requires id of your table you have no table with id jsonTable i think that is the problem

How to call a method from inside a jQuery .click() and keep context?

I want to have numerous "infoItem" elements which each have their own jQuery which manages them. Can anyone tell me why when I call "displayText()" that the elements inside that function are not the ones in the element which contains the click handler, but always the LAST element on the page?
<html>
<head>
<script type="text/javascript" src="systemJavascript/jquery-1.8.3.min.js"></script>
</head>
<body>
<div class="infoItem">
<div class="menu">
<span class="menuOne">one</span>
<span class="menuTwo">two</span>
</div>
<div class="content">intro message</div>
</div>
<div class="infoItem">
<div class="menu">
<span class="menuOne">eins</span>
<span class="menuTwo">zwei</span>
</div>
<div class="content">Introtext</div>
</div>
</body>
</html>
<script type="text/javascript">
var INFOITEM = INFOITEM || {};
INFOITEM.initialize = function(infoItem) {
var elemMenuOne;
var elemMenuTwo;
var elemContent;
this.defineVariables = function() {
elemMenuOne = infoItem.find('.menuOne');
elemMenuTwo = infoItem.find('.menuTwo');
elemContent = infoItem.find('.content');
}
this.decorateElements = function() {
elemMenuOne.css('background-color', 'beige');
this.decorateAsLink(elemMenuOne);
elemMenuTwo.css('background-color', 'beige');
this.decorateAsLink(elemMenuTwo);
}
this.functionalizeElements = function() {
that = this;
elemMenuOne.click(function(e) {
that.displayText('ONE');
});
elemMenuTwo.click(function(e) {
that.displayText('TWO');
});
}
this.displayText = function(text) {
elemContent.html('you selected ' + text);
}
this.decorateAsLink = function(elem) {
elem.css({
'cursor' :'pointer',
'text-decoration' : 'underline',
'font-weight' : 'normal'
});
}
this.defineVariables();
this.decorateElements();
this.functionalizeElements();
}
$('.infoItem').each(function(){
INFOITEM.initialize($(this));
});
</script>
INFOITEM is a global variable so you are resetting this for every item in your page, so it's always pointing at the last element:
$('.infoItem').each(function(){
INFOITEM.initialize($(this));
});
You'd be better off rolling this into a Jquery pluin type structure and then binding it to one element and passing in the associated element.
Here's a bolierplate to get you started:
http://stefangabos.ro/jquery/jquery-plugin-boilerplate-revisited/
The way I solved this was to add an ID to each element, and in the click events, fetch that item again, which I can then pass to any method where I can manipulate it appropriately, instead of the internal variables.
<html>
<head>
<script type="text/javascript" src="systemJavascript/jquery-1.8.3.min.js"></script>
</head>
<body>
<div id="infoItem_123" class="infoItem">
<div class="menu">
<span class="menuOne">one</span>
<span class="menuTwo">two</span>
</div>
<div class="content">intro message</div>
<div class="contentOne">you clicked one</div>
<div class="contentTwo">you clicked two</div>
</div>
<div id="infoItem_456" class="infoItem">
<div class="menu">
<span class="menuOne">eins</span>
<span class="menuTwo">zwei</span>
</div>
<div class="content">Introtext</div>
<div class="contentOne">du hast auf eins geklickt</div>
<div class="contentTwo">du hast auf zwei geklickt</div>
</div>
</body>
</html>
<script type="text/javascript">
var INFOITEM = INFOITEM || {};
INFOITEM.initialize = function(infoItem) {
var elemMenuOne;
var elemMenuTwo;
var elemContent;
var elemContentOne;
var elemContentTwo;
var itemId;
this.defineVariables = function() {
elemMenuOne = infoItem.find('.menuOne');
elemMenuTwo = infoItem.find('.menuTwo');
elemContent = infoItem.find('.content');
elemContentOne = infoItem.find('.contentOne');
elemContentTwo = infoItem.find('.contentTwo');
itemId = infoItem.attr('id');
}
this.decorateElements = function() {
elemMenuOne.css('background-color', 'beige');
this.decorateAsLink(elemMenuOne);
elemMenuTwo.css('background-color', 'beige');
this.decorateAsLink(elemMenuTwo);
elemContentOne.hide();
elemContentTwo.hide();
}
this.functionalizeElements = function() {
that = this;
elemMenuOne.click(function(e) {
that.displayText($('#'+itemId), elemContentOne.html());
});
elemMenuTwo.click(function(e) {
that.displayText($('#'+itemId), elemContentTwo.html());
});
}
this.displayText = function(clickedInfoItem, text) {
clickedInfoItem.find('.content').html(text);
}
this.decorateAsLink = function(elem) {
elem.css({
'cursor' :'pointer',
'text-decoration' : 'underline',
'font-weight' : 'normal'
});
}
this.defineVariables();
this.decorateElements();
this.functionalizeElements();
}
$('.infoItem').each(function(){
INFOITEM.initialize($(this));
});
</script>

Categories

Resources