I am struggling to find a way to get the name of the parent ID in a string. The code is part of a chat app written in Javascript and jQuery. Each time someone enters a message, the string outputs a block with username and text with a Close-x box before the username. When someone clicks the Close-x, it needs to grab the ID name of the parent div(json.innerdiv). The div with ID named json.outterdiv is the ID which allows me to delete the whole block message where as the json.innerdiv allows me to remove text, change text or just hide/show text. I tried searching on here for answers but all I ever get is undefined or null results.
My code:
var bubble = $('<div class="bubble-container" id="'+json.outterdiv+'"><span class="bubble"><div class="bubble-text" id="'+json.innerdiv+'"><p><div class="close-x" onclick="DelBubble(this)"></div>Some text</p></div></div>');
function DelBubble(clicked_id) {
alert($(this).parent().attr('id'));
}
Pass the event to onclick then get the closest of a class selector using jquery:
var bubble = `
<div class="bubble-container" id="2">
<span class="bubble">
<div class="bubble-text" id="3">
<p>
<div class="close-x" onclick="DelBubble(event)">
Close
</div>
Some text
</p>
</div>
</div>`;
$('body').append(bubble)
function DelBubble(e) {
const bubbleTextId = $(e.target).closest('.bubble-text').attr('id');
const bubbleContainerId = $(e.target).closest('.bubble-container').attr('id');
console.log({bubbleTextId,bubbleContainerId})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Related
I am a beginner in programming and am stuck in a problem. I want to find the last child (element) of parent (form). Then I want to insert an input element after the last child but it should be inside the form not after the form (outside). The form might contain input elements as well as select elements. How to accomplish it? I have tried the following ways but they don't work unfortunately.
var lastRepeatingGroup = $('.form-to-be-submitted:last'); // this one gives me the whole form meaning if I add something it will added at the end of the form
var lastRepeatingGroup = $('.form-to-be-submitted input:last'); //this gives me the last input element
var lastRepeatingGroup = $('.form-to-be-submitted input select').last(); //this does nothing, I think its an error
$newSection = $('<input type="button" value="newbutton" name="mybutton"/>');
newSection.insertAfter(lastRepeatingGroup); // when I use this statement it adds after the form not inside the form
So you just need some guidance on CSS Selectors and Jquery methods.
First lets look at:
The form might contain input elements as well as select elements.
So in CSS to do an or you need to use a comma:
input,select
if you are looking for direct descendants you need to use a >
form > input, form > select
These are then wrapped in jquery:
$('form > input, form > select')
Which yields all items, so we use last() to grab the last element:
var $last = $('form > input, form > select').last();
(if you don't need the > just remove it).
This was pretty close:
var lastRepeatingGroup = $('.form-to-be-submitted input select').last();
but it's looking for a select element in a input element in that class. Just needs a little adjustment:
var lastRepeatingGroup = $('.form-to-be-submitted input, .form-to-be-submitted select')
.last();
If you want to insert the element at the end of a specific element, you don't need to find the last item. Just use jquery's append
Except:
Consider the following HTML:
<h2>Greetings</h2>
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
You can create content and insert it into several elements at once:
$( ".inner" ).append( "<p>Test</p>" );
Each inner element gets this new content:
<h2>Greetings</h2>
<div class="container">
<div class="inner">
Hello
<p>Test</p>
</div>
<div class="inner">
Goodbye
<p>Test</p>
</div>
</div>
This should work:
$('.form-to-be-submitted').children().last()
.children() will select all the children in your form and .last() filters that further to only select the last child.
And to insert content after that element, just use .after() like:
$('.form-to-be-submitted').children().last().after('<input>')
Example:
$('.form-to-be-submitted').children().last().after('<input type="radio">')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-to-be-submitted">
<input type="text">
<input type="radio">
<input type="checkbox">
<select>
<option></option>
</select>
</form>
JQuery not needed. To insert a new element just before the end of the form, simply use .appendChild().
var frm = document.getElementById("theForm"); // Get reference to form
// Create a new element and configure it
var newElement = document.createElement("input");
newElement.id = "txtUser";
// Simply append it to the form.
frm.appendChild(newElement);
console.log(frm.elements[frm.elements.length-1]); // Get last element in form
<form id="theForm">
<input type="text">
<select>
<option>one</option>
<option>two</option>
<option>three</option>
</select>
<button type="button">Click Me</button>
</form>
How do I show a div (with classname) that is closest to my inputbox?
I have several inputboxes so i just need to display the specific inputbox.
In my example i want to show a div box above the input ( showing that the inputbox has wrong content i.e Numbers and not Letters ) if the inputbox has letters, the div must hide again.
So it should be a normal error report.
My Code is following:
https://jsfiddle.net/1mvb3wko/
function calculate(){
var regex = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?()]/);
var letter = /[a-zA-Z ]+/;
error1 = false;
error2 = false;
error3 = false;
var input = ['ID1','ID2'];
var element;
for(i=0;i <element.length; i++{
element = document.getElementById(input[i]);
if(regex.test(element.value) && letter.test(element.value)){
element.style.border = '4px solid red';
//Here's where i'm stuck
//i'm trying to SHOW the previous Div with class(Errorreport) if the input is wrong
//$(element).prev('.Errorreport').show(); doesn't work
}
}
}
Since there are already answers talking about the use of .closest I;m going to take a different approach and suggest that you remove all of those unnecessary <div> elements and focus on what you want to achieve. You want an error message to be displayed when the user types something wrong in one of the inputs.
You are better of using spans or labels, those are the elements that are often used to display form errors.
So you want a way to select all inputs. All of them have a .form-control class so you can use jQuery:
$('.form-control')
Watch for the change or blur events, whatever suits your needs and use jQuery's .parent() and .find() to find the error message and show it.
I changed a lot of your code to be cleaner and more descriptive of what it does:
https://jsfiddle.net/uf72taeu/2/
What you expected is there, just change if condition. By default I made it true.
function calculate(element) {
var regex = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?()]/);
var letter = /[a-zA-Z ]+/;
var inputBox = $(element);//$('#'+input[i]);
if (true/* regex.test(element.value) && letter.test(element.value) */)
{
var par = inputBox.parent(); // will return enclosed div
par = par.parent();// will return div with class 'row'
var errReport = par.prev(); // will return previous div, which is div with class 'row Errorreport'
// do whatever in errReport
errReport.css("display", "block");
inputBox.css("border", "4px solid red");
}
// }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row Errorreport" style="display: none;">
<div>Error id 1</div>
</div>
<div class="row">
<div>
<input class="autoausgabe form-control " id="ID1"
onChange="calculate(this);">
</div>
</div>
<div class="row Errorreport" style="display: none;">
<div>Error id 2</div>
</div>
<div class="row">
<div>
<input class="autoausgabe form-control " id="ID2"
onChange="calculate(this);">
</div>
</div>
I've done quite a bit of research for this but can't get my mind around it.
There is a parent div .container. Which has numerous child divs having different text inside them. There are two buttons outside the .container. One is used to dynamically create and append a child element having particular text. Other is to remove a child div having particular text.
The first time the page is loaded everything works but when a new child div is added (lets say having text xyz) and then use enters xyz in textarea and presses remove button (which is coded to remove child div having text xyz in them) it doesn't work.
Sample HTML markup (there may be infinite number of child divs)
<div class="container>
<div class="child1"></div>
<div class="child2"></div>
<div class="child3"></div>
<div class="child4"></div>
</div>
<button class="AppendWithSomeText"></button>
<button class="RemoveDivWithSomeMatchedText"></button>
<textarea></textarea>
jquery for adding the div
var newdiv = = document.createElement('div');
newdiv.className = 'child';
$(".container").append(newdiv);
$(".container").find(".child").html(textfromtextarea);
// here text from text area is a string stored from user input in textarea
jQuery for remove button
$('.container>div:contains("'+textfromtextarea+'")').remove();
//works only first time
http://codepen.io/dustinpoissant/pen/VYXGwB
HTML
<input type='text' id='input' />
<button onclick='addItem()'>Add</button>
<button onclick='removeItem()'>Remove</button>
<br><br>
<div id='box'></div>
JavaScript
function addItem(){
$("#box").append("<span>"+$("#input").val();+"</span>");
}
function removeItem(){
var text = $("#input").val();
$("#box span").each(function(i, el){
if($(el).text()==text) $(el).remove();
});
}
Inorder to keep the uniformity of structure I have added class of type child-number.
I hope this is what you expected.
$(document).ready(function() {
$(".AppendWithSomeText").on("click", function() {
$(".container").append("<div class=child" + ($("[class^='child']").length + 1) + ">" + $(".content").val() + "</div>")
})
$(".RemoveDivWithSomeMatchedText").on("click", function() {
$('.container>div:contains("' + $(".content").val() + '")').remove();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
<div class="child1">somecontent</div>
<div class="child2">somecontent</div>
<div class="child3">somecontent</div>
<div class="child4">somecontent</div>
</div>
<button class="AppendWithSomeText">add</button>
<button class="RemoveDivWithSomeMatchedText">remove</button>
<textarea class="content"></textarea>
The thing I have tried so far is
<h3>This is what I want to display inside "ppname"</h3><a class="" href="javascript:" code="displayed">HO</a>
<h3>Just for test</h3>
<div class="pp" style="display:none;">Not
<div class="ppname"></div>
<div class="ppcode"></div>
</div>
The Jquery
$('a[code]').click(function () {
$('.ppcode').html($(this).attr('code'));
$('.ppname').html($(this).closest("h3").html());
$('.pp').show();
});
$('span.close').click(function () {
$('.pp').hide();
});
The text in attribute code is displaying inside the div with class ppcode but the text in h3 is not displaying inside div with class ppname.
Thanks
Use prev instead of closest to display the sentence This is what I want to display inside "ppname" in the ppname-container:
$('.ppname').html($(this).prev().html());
I'm making a page that will generate a table of divs. Each row has a cell with a link. When that link is clicked a hidden div between the current row and the next will toggleSlide out.
The link will have id="clickLink_10" and the hidden div will have id="10" and class="hiddenDiv". The number 10 is a dynamic number generated form the id of the post in the database.
I have the animation working fine, as long as I hard code the numbers. But I want to connect the link to it's hidden div dynamically, since the rows will be fetched from a database.
Here's an example of how the html may look (it's more complicated in reality, but this is the key part):
<div>CLICK HERE</div>
<div class="hiddenDiv" id="11">blabla</div>
<div>CLICK HERE</div>
<div class="hiddenDiv" id="1">blabla</div>
<div>CLICK HERE</div>
<div class="hiddenDiv" id="3">blabla</div>
And here's what I'm trying to do in jQuery:
hiddenDivs = $('.hiddenDiv');
for(var i = 0; i < hiddenDivs.length; i++ ) {
$("#clickLink_" + hiddenDivs[i].id).click( function() {
$(hiddenDivs[i]).slideToggle(1000);
});
}
Which won't work obviously.I know I'm treating the i-variable wrong so view this a s dummy code. Very grateful for any help.
A valid option could be using data- attributes. I'll also change your numeric ids as only numbers is not a valid html id.
HTML
<div>CLICK HERE</div>
<div class="hiddenDiv" id="hidden_11">
<div>CLICK HERE</div>
<div class="hiddenDiv" id="hidden_1">
<div>CLICK HERE</div>
<div class="hiddenDiv" id="hidden_3">
JS
$(".clickLink").click( function() {
var hiddenDivId = "hidden_" + $(this).data("hidden-id");
$("#" + hiddenDivId ).slideToggle(1000);
});
You can use the ^= operator with an attribute selector to select elements. the ^= operator tells it to look for the attribute that "starts with" something, so:
$("a[id^=comment_]").click(function(e){
e.preventDefault();
var hideId = $(this).attr("id").replace("comment_","");
$("#"+hideId).slideToggle(1000);
});
So the selector a[id^=comment_] is basically saying select all anchor tags that have an id that start with comment_