Javascript to check if div has child with that classname [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So,
How to check with JavaScript if DIV has that classname? Here's an example HTML
<div class="cart"></div> that would be the parent and then JavaScript creates under that div's upon a click, but if it's already there and you click the item then it's just going to remove it. Example: Button is yellow and if you click it, it add's item to the cart and changes button class to selected. If you click it again, it will remove selected class and also remove item from the cart. I do have a code for the clicking part and adding it to cart, but not for removing it.. How could I do it?
JavaScript
$(".item-card").mousedown(function() {
$(this).toggleClass("selected-item");
var itemnume = $(this).find("img").attr("title");
$("#itemcart").append($("<div id="+itemnume+">"+itemnume+"</div>"));
});
Here it adds the item to the cart, but if you would reclick it, it will do it again. I've tried write a function, which checks that is the item already in cart, if it is then remove it, if not then add it, but I never succeed. I think that would solve my problem though.

try the following:
$(".item-card").click(function() {
var itemnume = $(this).find("img").attr("title");
var replaced = itemnume.split(' ').join('_');
if ($(this).hasClass('selected-item')) {
console.log()
$("#" + replaced).remove();
} else {
$("#itemcart").append($("<div id=" + replaced + ">" + itemnume + "</div>"));
}
$(this).toggleClass("selected-item");
});
https://jsfiddle.net/0tusd19b/

Related

jquery get value of specific number inputs in while loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last month.
Improve this question
what the result looks like
I'm making a product inventory system; where I can simple change the value with number inputs, hit the checkmark, and be done. But I'm having trouble getting the specific value.
php:
<?php
$get_prod = $con->query("SELECT * FROM products");
while($get = mysqli_fetch_array($get_prod)){
echo '
<div class="prod-inv">
<div class="prod-inv-top">
<h1>'.$get['prod_name'].'</h1>
<h2>'.$get['prod_price'].'</h2>
</div>
<div class="prod-inv-body">
<img class="image-manage" src="'.$get['prod_cover'].'">
<input id="'.$get['prod_id'].'" type="number" class="num" value="1"/>
<button id="'.$get['prod_name'].'" class="btn search">✓</button></a>
</div>
</div>';
}
?>
jquery:
<script type="text/javascript">
$("button").click(function() {
var target = this.id;
var value = $(target).val();;
alert(value);
});
</script>
I've tried everything from form GET, to href links, now jquery. So far nothing has yelded results.
[1] Firstly, I'm not familiar with PHP, but it seems that closing anchor tag mistakenly presents in the markup:
<button id="'.$get['prod_name'].'" class="btn search">✓</button></a>
Or maybe opening anchor tag is missing...
[2] Secondly, in following line:
var target = this.id;
context "this" is currently clicked button, this code takes clicked button id and then in this line:
$(target)
you're taking currently clicked button DOM element by it's id, but it is already stored in "this"
[3] when you want to query element by id, you have to prepend it with hash "#":
$('#' + target)
So, you see the issue, when button is clicked, you take it's id, then find this button on the page again by it's id and then try to take .val() from a button (which actually does not have a value, it is not an input)
Suppose, you wanted to achieve following:
button is clicked -> find input near this button -> take value of this input
$('button').click(function () {
var value = $(this).closest('.prod-inv-body').find('input').val();
console.log(value);
});

use large size array to create element and then insert it into div using javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a javascript array of size 40000 containing objects like this one
[{previousId:null,id:1,nextId:2,imageName:"2017_10001018.jpg"}]
I am creating a survey form out of this. I have a function createElement(data,hide[boolean]). It will return an element that will be inserted inside the div. According to this function, only the first object will be visible rest will be hidden using CSS class "hide". Users will be navigating using the next and previous buttons to insert data in the form.
When I use for loop to call this function for each data then the page gets hanged. Is there any way that I insert data inside the dom without making the page hang?
You should not use hide to do that because it still renders 40,000 elements and it severely impacts the performance.
What you should try something like this:
const data = [];
let currentItem = 0;
// Populates the data
for (let i = 0; i < 40_000; i++) {
data.push(`item #${i}`);
}
// Render only ONE item
function createElement(item) {
document.getElementById('currentItem').innerText = item;
}
// Replaces the current item with the next one
function onNextButtonClick() {
// Prevent index overflows
if (currentItem >= data.length) return;
createElement(data[currentItem]);
currentItem += 1;
}
// Give it an initial load to load the first item
onNextButtonClick();
Item:
<div id="currentItem"></div>
<br />
<button onClick="onNextButtonClick()">Next</button>
What it does is it selects the first item in the data and render that on the page. After the user click the button and the button calls onNextButtonClick(), it replaces the old data with the new data. This way you don't render all 40,000 items.
This is not the perfect solution but it'll be much more performant than rendering 40,000 items.
If you want to go further, I think concepts like paging is a place to take a look at.

I don't understand the concept of this function in Javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
for example, you would have
<input id="searchbox" type="text" value="Type Here..." />
<button id="clickbait">Click Me</button>
<div id="emptydiv">sda</div>
<script type="text/javascript">
var clickthis="clickbait";
var searchinput=document.getElementById("searchbox").value;
var generate="emptydiv";
document.getElementById(clickthis).onclick=function () {
searchinput=document.getElementById("searchbox").value;
document.getElementById(generate).innerHTML=searchinput;
}
</script>
So this is pretty much just something to change the text in the empty div to whatever is in the text field when you click on the button but I don't understand the "idea" of what's going on here. I already set the var to a value so why do you need to grab the value again?
I can understand the other basics so far like document(refers to the whole page) then getelementbyid(refers to the element) and then on the click you want it to perform a function but everything after that is confusing.
I already set the var to a value so why do you need to grab the value
again?
When you set the searchinput value first before the onclick assignment, you fetched and assigned the value of searchinput at that time.
Inside the click event handler, you are getting the value in searchinput when the div is clicked so the value at that time might be different.
When its firing click event then searchinput=document.getElementById("searchbox").value;
that means searachinput is what everever typed in the input feild
and then that value is being reassigned to
document.getElementById(generate).innerHTML=searchinput;
`
When the button is clicked fire the event:
document.getElementById(clickthis).onclick=function ()
Get the value of 'searchBox':
searchinput=document.getElementById("searchbox").value;
Assign what ever was in the 'searchBox' as HTML in 'emptyDiv'
document.getElementById(generate).innerHTML=searchinput;
Just to note that:
searchinput=document.getElementById("searchbox").value;
Is actually redundant because you are already declaring it with the other vars.
So your code should look like this:
document.getElementById('clickbait').onclick=function () {
var searchinput = document.getElementById("searchbox").value;
document.getElementById('emptydiv).innerHTML=searchinput;
}
Or to make it even simpler and cut it down to 2 lines you could even use jQuery:
$('#clickbait').on('click', function(){
$('#emptydiv').innerHTML = $('#searchbox').value;
}
It copies the value of input into the "emptydiv" div when you click on the button.
Why is the real good question, here, IMO.

Adding row in html table using select box [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I wish to make an html table with a select box below the table. If you select an option from the select box it gets added in the table with no duplicate entries. Also the select box needs to be properly formatted.
What I am looking for is to be able to fetch data into the option column with proper tabular formatting as seen in the image. Length of the words should not change the formatting which is not possible to achieve by adding white spaces.
#Tarekis posted an answer with the jsFiddle . Though it solved majority of my problem, the formatting part is still a problem.
Okay here's the thing.
When you change your option you have to go trough a couple of things.
First you get the Data of the Option and make it in a Array.
// Select the text of the chosen option
var text = $(this).children(":selected").html();
// Create a regex to split the string
var regex = new RegExp(" *");
// Make an array out of the string
// The cleanArray() function is in the JSFiddle
var array = cleanArray(text.split(regex));
Now you have an Array of the Values you want to add.
Next step is to create the HTML you want to add to your tbody.
// Create a new <tr> to append to the tbody
var newRowHTML = "<tr>";
$.each(array,function(){
newRowHTML += "<td>"+this+"</td>";
});
newRowHTML += "<tr>";
Now loop trough your td's and see if the ID of the Option you clicked is alreay there.
var alreadyInTable = false;
$.each($("tbody tr > td:first-child"),function(){
if(array[0] == $(this).html()){
// If this ID is alreay in the table set the bool to true
alreadyInTable = true;
}
});
And add the HTML.
if(alreadyInTable == false){
$("tbody #select").before(newRowHTML);
}
Important Notes: If you do not read and apply these dependencies the code will not work!
To use this you cannot have any whitespaces or new lines in your option. This means it has to look like:
<option>thecompletetextwithoutanywhitespacesbetweenthedata</option>
Also you have to add id="select" to the tr containing the select, as it is the one after where you display your data, so you can use $("tbody #select").before(newRowHTML) as shown before.
You have to make the "+ Add new Line" selected as you can see in the Fiddle's HTML, since the new Rows only get added on a change of the select, so you cannot just click the row you have already selected as it does not change which one you have selected.
And here is a complete JSFiddle!
$('#my-select-element').change(function(){
// here goes the code to append a <tr></tr> element to the table
});

Finding corresponding value in <select> tag and displaying it [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
What I want to achieve it is when someone select any option from the column 1 dropdown list, it should search for corresponding option in 2nd column and display its value in the 3rd column.
For example, suppose someone selected value 3 from the column 1 dropdown list, the corresponding value to be displayed in column 3 would be 30.
I don't know how to achieve this - can someone guide me a bit? Here's what I have so far:
$(document).ready(function () {
$("tbody tr td:nth-of-type(1)").on('change blur input', function() {
});
});
If you'd like, here's my JSFiddle.
$(document).ready(function () {
$("tbody tr td:nth-of-type(1) select").on("change", function () {
var thistext = $(this).find(":selected").text().toLowerCase();
var nexttext = $(this).closest("td").next().find("option[value='" + thistext + "']").text();
$(this).closest("td").siblings().eq(1).text(nexttext);
});
});
First, you need to put the handler on the <select> element, not the <td>.
Then, to find the corresponding option in the second menu, I find the one whose value is equal to the lowercase text in the selected option. Then I take its text and put it in the third column.
If that's not what you wanted, maybe you can clarify in the question about what you mean by corresponding options.
FIDDLE
You can get the index of the selected item in a select via selectedIndex. Assuming this is the select, you can have this code:
var index = this.selectedIndex;
You can then use jQuery's .eq() to find the right option in the other select elements and grab the text using text()
Here's a demo
$(document).ready(function () {
$("tbody tr td:nth-of-type(1)").on('change', 'select',function (e) {
var index = this.selectedIndex;
var parentTd = $(this).closest('td');
var nextTd = parentTd.next();
var text = nextTd.find('select > option').eq(index-1).prop('selected','selected').text();
nextTd.next().text(text);
});
});

Categories

Resources