How to insert text into one textarea out of several with id? - javascript

I have two textareas with different ids which both have wysiwyg buttons for text formatting. I can insert the formatting tags into the first textarea however when I try to insert tags into the second textarea, the tags are inserted into the first one. Obviously when I use the buttons assigned to their respective textarea I would like the format tags to be inserted in the appropriate textarea. In jQuery I try to store the id of the buttons to concatenated with '#textarea' to recreate the textarea id.
<button class="B" id="11">B</button>
<button class="I" id="11">I</button>
<button class="U" id="11">U</button>
<button class="S" id="11">S</button>
<div id="textarea1" class="textareaWrapper">
<textarea id="textarea11" class="textarea"></textarea>
</div>
<button class="B" id="22">B</button>
<button class="I" id="22">I</button>
<button class="U" id="22">U</button>
<button class="S" id="22">S</button>
<div id="textarea2" class="textareaWrapper">
<textarea id="textarea22" class="textarea"></textarea>
</div>
<script>
$(document).ready(function () {
$('button.B').click(function () {
var id = $('button.B').attr('id');
$('#textarea' + id).val($('#textarea' + id).val() + id);
})
$('button.I').click(function () {
var id = $('button.I').attr('id');
$('#textarea' + id).val($('#textarea' + id).val() + "<i></i>");
})
$('button.U').click(function () {
var id = $('button.U').attr('id');
$('#textarea' + id).val($('#textarea' + id).val() + "<u></u>");
})
$('button.S').click(function () {
var id = $('button.S').attr('id');
$('#textarea' + id).val($('#textarea' + id).val() + "<s></s>");
})
})
</script>

The problem is that inside your click handler you're getting a ref to the first button's id.
try this: $(this).attr('id');
Like:
$(document).ready(function () {
$('button.B').click(function () {
var id = $(this).attr('id');
$('#textarea' + id).val($('#textarea' + id).val() + id);
})
$('button.I').click(function () {
var id = $(this).attr('id');
$('#textarea' + id).val($('#textarea' + id).val() + "<i></i>");
})
$('button.U').click(function () {
var id = $(this).attr('id');
$('#textarea' + id).val($('#textarea' + id).val() + "<u></u>");
})
$('button.S').click(function () {
var id = $(this).attr('id');
$('#textarea' + id).val($('#textarea' + id).val() + "<s></s>");
})
})

You must not use same ids for multiple controls.
My suggestion is to use dummy attribute e.g.'data-group', which can be used in JavaScript and browser simply ignores it. Like:
<button class="B" data-group="1">B</button>
<button class="I" data-group="1">I</button>
<button class="U" data-group="1">U</button>
<button class="S" data-group="1">S</button>
<div id="textarea1" class="textareaWrapper">
<textarea id="textarea11" class="textarea"></textarea>
</div>
<button class="B" data-group="2">B</button>
<button class="I" data-group="2">I</button>
<button class="U" data-group="2">U</button>
<button class="S" data-group="2">S</button>
<div id="textarea2" class="textareaWrapper">
<textarea id="textarea22" class="textarea"></textarea>
</div>
<script>
$(document).ready(function () {
$('button.B').click(function () {
var grp = $('button.B').attr('data-group');
$('#textarea' + grp).val($('#textarea' + grp).val() + id);
})
$('button.I').click(function () {
var grp = $('button.I').attr('data-group');
$('#textarea' + grp).val($('#textarea' + grp).val() + "<i></i>");
})
$('button.U').click(function () {
var grp = $('button.U').attr('data-group');
$('#textarea' + grp).val($('#textarea' + grp).val() + "<u></u>");
})
$('button.S').click(function () {
var grp = $('button.S').attr('data-group');
$('#textarea' + grp).val($('#textarea' + grp).val() + "<s></s>");
})
})
</script>
Hope it works.

The problem is the way you retrieve your ids:
$('button.S').attr('id');
This will get the id of the first element passing the selector. Consider this JSFiddle.

Related

How do I compare the value

When I click on the buttons successfully added, how do I add the value to previous value when the button is clicked more than once.
$(document).ready(function() {
$('.btn').click(function() {
var btn = $(this);
var count = btn.data("count");
var name = btn.data("name");
var price = btn.data("price")
console.log(name + price)
$('.display').append('<h2>' + name + '</h2> ' + count + ' pc. price = ' + price)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-name="Buterbrod" data-price="140" data-count="1" class="btn" type='submit'>
<p>Buterbrod</p>
<p class="price">140</p>
</button>
<button data-name="hotdog" data-price="110" data-count="1" class="btn" type='submit'>
<p>hotdog</p>
<p class="price">110</p>
</button>
<div class="display"></div>
Just create the container to hold the expected value from the start, but fill it's price and number with zeroes. Then when the buttons are clicked just add those number.
Edit 1: If you have too many products for this, just dynamically add those 'zero container' with 'if not exist' logic
Edit 2: It is recommended to represent each product with an ID. The ID may be database primary key, slug, or anything that doesn't contain space or is numeric.
$( document ).ready(function() {
//$('.container_product').css('display','none');
$('.btn').click(function(){
var btn = $(this);
var count = btn.data("count");
var identifier = btn.data("identifier");
var name = btn.data("name");
var price = btn.data("price")
//console.log(name + price)
//$('.display').append('<h2>'+ name + '</h2> ' + count + ' pc. price = ' + price)
if($("#container_"+identifier).length == 0) { // if not exist
$(".display").append(`
<span id="container_`+identifier+`" class="container_product">
<h2>`+name+`</h2>
<span id="num_`+identifier+`">0</span> pc.
price = <span id="price_`+identifier+`">0</span>
</span>
`)
}
$("#container_"+identifier).css('display','block');
$("#price_"+identifier).html( parseInt($("#price_"+identifier).html())+price );
$("#num_"+identifier).html( parseInt($("#num_"+identifier).html())+1 );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-name="buterbrod" data-price="140" data-count="1" data-identifier="1" class="btn" type='submit'>
<p>Buterbrod</p>
<p class="price">140</p>
</button>
<button data-name="hotdog" data-price="110" data-count="1" data-identifier="2" class="btn" type='submit'>
<p>hotdog</p>
<p class="price">110</p>
</button>
<button data-name="double buterbrod" data-price="9999" data-count="1" data-identifier="3" class="btn" type='submit'>
<p>double buterbrod</p>
<p class="price">9999</p>
</button>
<div class="display">
</div>
It can easily be done using your code, append the content in a container a give that a class, next time just check if that container already exist then insert the html into that. Plus you also need to keep updating the count variable.
$(document).ready(function() {
$('.btn').click(function() {
var btn = $(this);
var data = btn.data();
var count = data.count;
var name = data.name;
var price = data.price * count;
data.count = count + 1;
var html = '<h2>' + name + '</h2> ' + count + ' pc. price = ' + price;
name = name.split(" ").join("_");
if($('.display').find("."+name).length)
$('.display').find("."+name).html(html);
else
$('.display').append($("<div class='"+name+"'></div>").html(html));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-name="Buterbrod" data-price="140" data-count="1" class="btn" type='submit'>
<p>Buterbrod</p>
<p class="price">140</p>
</button>
<button data-name="hotdog" data-price="110" data-count="1" class="btn" type='submit'>
<p>hotdog</p>
<p class="price">110</p>
</button>
<div class="display"></div>
Find the appended element first into the 'display' element, if its length is 0 then directly append it, else first get the value of data-price attribute and add your updated price to it.
$(document).ready(function() {
$('.btn').click(function() {
var btn = $(this);
var count = Number(btn.data("count"));
var name = btn.data("name");
var price = Number(btn.data("price"));
var $h2 = $("<h2></h2>")
.attr('data-name', name)
.attr('data-count', count)
.attr('data-price', price)
.text(name + ' ' + count + ' pc. price = ' + price);
var dataNameSelector = '*[data-name=' + name + ']';
var childrenOrders = $('.display').find(dataNameSelector);
if (childrenOrders.length === 0) {
$('.display').append($h2);
} else {
var updatedPrice = Number(childrenOrders.data('price')) + price;
var updatedCount = Number(childrenOrders.data('count')) + count;
childrenOrders.data('price', updatedPrice);
childrenOrders.data('count', updatedCount);
childrenOrders.text(name + ' ' + updatedCount + ' pc. price = ' + updatedPrice);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-name="Buterbrod" data-price="140" data-count="1" class="btn" type='submit'>
<p>Buterbrod</p>
<p class="price">140</p>
</button>
<button data-name="hotdog" data-price="110" data-count="1" class="btn" type='submit'>
<p>hotdog</p>
<p class="price">110</p>
</button>
<div class="display"></div>

jquery edit post doesn't work

I am trying to make a edit post using jquery. But my code doesn't worked.
It need to work when i click the edit button then the editMarkUp wil be put in messageB1 but it doesn't work.
Anyone can help me here what i am missing and what is the solution?
This is DEMO from jsfiddle.net
Js
$(document).ready(function() {
$("body").on("click", ".editBtn", function() {
var ID = $(this).attr("id");
var currentMessage = $("#messageB" + ID + " .postInfo").html();
var editMarkUp = '<textarea rows="5" cols="80" id="txtmessage_' + ID + '">' + currentMessage + '</textarea><button name="ok" ">Save</button><button name="cancel">Cancel</button>';
$("#messageB" + ID + " .postInfo").html(editMarkUp);
});
});
HTML
<div class="container">
<div class="postAr" id="messageB1">
<div class="postInfo">
fdasfads fasd fadsf adsf adsf adsf asd fasd f dfsa
</div>
<div class="editBtn" id="1">Edit</div>
</div>
</div>
You're not defining editobj variable anywhere in your code, and I guess you probably meant .postInfo instead:
$(document).ready(function() {
$("body").on("click", ".editBtn", function() {
var ID = $(this).attr("id");
$('.postInfo').prop('disabled', 'true');
var currentMessage = $("#messageB" + ID + " .postInfo").html();
var editMarkUp = '<textarea rows="5" cols="80" id="txtmessage_' + ID + '">' + currentMessage + '</textarea><button name="ok" ">Save</button><button name="cancel">Cancel</button>';
$("#messageB" + ID + " .postInfo").html(editMarkUp);
});
});
MODIFIED DEMO

New divs not creating from a newly created div

I want to remove the addcontent button once a new div is created.
Then create new divs from the new addcontent button created inside a new div.
<script>
var i = 1;
$(document).ready(function () {
$("#addcontent").click(function () {
var q = "new-question" + String(i);
alert(q);
$(".question").append('<div class="new-question" id="question' + i + '" name="question' + i + '"><b>Div is created</b><br> This is div text <br> <button id="addcontent">Add content</button></div>').show('slow');
i++;
});
});
</script>
<div class="question">
<button id="addcontent">Add content</button>
</div>
try this:
<script>
var i = 1;
$(document).ready(function () {
$(document).on('click','.addcontent',function(){
//$(".addcontent").click(function () {
if(i==1)
$(".question").html('');
var q = "new-question" + String(i);
$(".hide_button").remove();
alert(q);
$(".question").append('<div class="new-question" id="question' + i + '" name="question' + i + '"><b>Div is created</b><br> This is div text <br> <button class="addcontent hide_button">Add content</button></div>').show('slow');
i++;
});
});
</script>
<div class="question">
<button class="addcontent hide_button">Add content</button>
</div>
Just in case you want to have div inside div questions:
var i = 1;
$(document).ready(function () {
$('.question').on('click', 'button#addcontent', function () {
var $parent = $(this).parent();
$(this).remove();
var q = "new-question" + String(i);
alert(q);
$parent.append('<div class="new-question" id="question' + i + '" name="question' + i + '"><b>Div is created</b><br> This is div text <br> <button id="addcontent">Add content</button></div>').show('slow');
i++;
});
});
See demo

Uncheck checkbox with close button

Please, advice.
I want to add tags inside the container marking checkboxes and remove tags by clicking on the "x" button of each tag.
Everything works fine except that when you click on the "x" button and tags are removed the state of the checkbox remains checked.
But I need that when you click on the button of each tag the state of the checkbox must be unchecked.
It might be easier to do with the value and the name of input, but I can't use them - only id.
$(document).ready(function() {
var $list = $("#itemList");
$(".chkbox").change(function() {
var a = $('label[for="' + this.id + '"]').text();
if (this.checked) {
$list.append('<li>'+a+'<button class="closebutton" value="'+a+'">X</button></li>');
}
else {
$("#itemList li:contains('"+a+"')").remove();
}
})
$(document).on('click','.closebutton',function(){
var b = this.value;
$("#itemList li:contains('"+b+"')").remove();
$('label[for="' + this.id + '"]').removeAttr('checked');
});
});
<div id="items">
<ul id="itemList">
</ul>
</div>
<div id="tab1" class="tab-pane">
<div id="ck-button"><label for="one"><input type="checkbox" id="one" class="chkbox"><span>First book</span></label> </div>
<div id="ck-button"><label for="two"><input type="checkbox" class="chkbox" id="two"><span> Second book</span></label> </div>
</div>
Try
$(document).ready(function () {
var $list = $("#itemList");
$(".chkbox").change(function () {
var a = $(this).next().text();
if (this.checked) {
$('<li>' + a + '<button class="closebutton" value="' + a + '">X</button></li>').appendTo($list).data('src', this);
} else {
$("#itemList li:contains('" + a + "')").remove();
}
})
$(document).on('click', '.closebutton', function () {
var $li = $(this).closest('li');
$($li.data('src')).prop('checked', false);
$li.remove();
});
});
Demo: Fiddle
Try this:
<div id="items">
<ul id="itemList">
</ul>
</div>
<div id="tab1" class="tab-pane">
<div id="ck-button1"><label for="one"><input type="checkbox" id="one" class="chkbox"><span>First book</span></label>
</div>
<div id="ck-button2">
<label for="two"><input type="checkbox" class="chkbox" id="two"><span> Second book</span></label></div>
</div>
</body>
<script>
$(document).ready(function()
{
var $list = $("#itemList");
$(".chkbox").change(function()
{
var a = $('label[for="'+this.id+'"]').text();
var t = this.id;
if(this.checked)
{
$list.append('<li>'+a+'<button class="closebutton" title="'+t+'" value="'+a+'">X</button></li>');
}
else
{
$("#itemList li:contains('"+a+"')").remove();
}
})
$(document).on('click', '.closebutton', function()
{
var b = this.value;
var q = this;
$("#itemList li:contains('"+b+"')").remove();
$('#'+this.title).removeAttr('checked');
});
});
</script>
Or See this demo: http://jsfiddle.net/knYvf/
API used:
find: http://api.jquery.com/find/
contains: http://api.jquery.com/contains-selector/
This line should do the trick:
$('label:contains("' + b + '")').find('.chkbox').prop('checked', false);
+1 to you for neat question as well!
Hope any will suffice the need :)
Code
$(document).ready(function () {
var $list = $("#itemList");
$(".chkbox").change(function () {
var a = $('label[for="' + this.id + '"]').text();
if (this.checked) {
$list.append('<li>' + a + '<button class="closebutton" value="' + a + '">X</button></li>');
} else {
$("#itemList li:contains('" + a + "')").remove();
}
})
$(document).on('click', '.closebutton', function () {
var b = this.value;
$("#itemList li:contains('" + b + "')").remove();
$('label:contains("' + b + '")').find('.chkbox').prop('checked', false);
});
});
<div id="items">
<ul id="itemList"></ul>
</div>
<div id="tab1" class="tab-pane">
<div id="ck-button">
<!--html code should be like this no need to add span-->
<input type="checkbox" id="one" class="chkbox"/>
<label for="one">First book</label>
</div>
<div id="ck-button">
<input type="checkbox" class="chkbox" id="two" />
<label for="two"> Second book</label>
</div>
var $list = $("#itemList");
$(".chkbox").change(function () {
var a = $('label[for="' + this.id + '"]').text();
var name=$(this).attr('id');
if (this.checked) {
//add name attribute in the button with the id of checkbox
$list.append('<li>' + a + '
<button class="closebutton" value="' + a + '" name="'+name+'">X</button></li>');
} else {
$("#itemList li:contains('" + a + "')").remove();
}
})
$(document).on('click', '.closebutton', function () {
var b = this.value;
$("#itemList li:contains('" + b + "')").remove();
//remove the checkbox whose id is same as the name attribute of button
$(':checkbox[id="' + this.name + '"]').removeAttr('checked');
});
DEMO

Build a array of div's id using each DIV inside section

I'm trying to get the ID of each DIV inside this HTML code
<section id="choices">
<div id="talla_choice_24" style="">
...
</div>
<div id="color_choice_25" style="">
...
</div>
<div id="sport_choice_26" style="">
...
</div>
<button type="button" class="create-variation" id="create-variation" style="">Crear variaciones</button>
<section id="variations_holder" style="display: none"></section>
</section>
So I made this:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push($(this).val());
})
return inputValues;
}
And I call here:
$('#choices').on("click", "#create-variation", function(e) {
var parent_id = $(this).closest("section").attr("id");
var element = getDivId(parent_id);
iterateChoices("", element[0], element.slice(1), 0);
});
I need to build something like this:
var element = new Array($('#talla_choice_24 input:text'), $('#color_choice_25 input:text'), $('#sport_choice_26 input:text'));
But I get this error:
Uncaught TypeError: Object has no method 'each'
What is wrong?
UPDATE
This is the code for iterateChoices() function:
function iterateChoices(row, element, choices, counter) {
if ($.isArray(choices) && choices.length > 0) {
element.each(function(index, item) {
if (counter == 0)
row = '<input type="text" required="required" value="" name="pupc[]" /><input type="text" required="required" value="" name="pprice[]" /><input type="text" required="required" value="" name="pqty[]" />';
iterateChoices(row + '<input value="' + item.value + '">', choices[0], choices.slice(1), counter + 1);
});
} else {
html_temp = "";
$.each(element, function(index, item) {
html_temp += row + '<input value="' + item.value + '"><br>';
});
html += html_temp;
}
}
I also made some changes at this code:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push("#" + $(this).attr('id') + ' input:text');
});
return inputValues;
}
And now the error change to this:
Uncaught TypeError: Object #talla_choice_24 input:text has no method 'each'
UPDATE 2
I still continue change getDivId() function to build a array like this:
var element = new Array($('#talla_choice_24 input:text'), $('#color_choice_25 input:text'), $('#number_choice_23 input:text'), $('#sport_choice_23 input:text'));
But can't get it since array values are constructed as strings, see below:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push('$("#' + $(this).attr('id') + ' input:text")');
});
return inputValues;
}
I'm getting:
("$('#talla_choice_24 input:text')", "$('#color_choice_25 input:text')")
I think there is the problem
You are using the val method on a div element, which just returns an empty string. There is no each method on a string.
You don't need the id of each div to get the input elements inside them. This will get you the inputs in a single jQuery object:
var element = $(this).closest("section").find("> div input:text");
If you really need an array of separate jQuery objects, you can then do this:
element = element.map(function(){ return $(this); }).get();
var arr = [];
$("#create-variation").on('click', function(){
$("#choices > div").each(function(a,b){
arr.push($(this).text());
});
});
After some headaches I realized how to fix the (my) error, here is the solution to all the problems:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push($("#" + $(this).attr('id') + " input:text"));
});
return inputValues;
}

Categories

Resources