I want to add a p tag in a div tag when I click a button, and also when I click on a p tag i want to delete the p tag I clicked on.
This is my Jquery:
$('#ajou').click(function(){
alert( $('#skill').val());
$('#skills').append('<p>'+$('#skill').val()+'</p>');
});
$("p").click(function(){
$(this).remove();
});`
And this is my HTML:
<input type="text" id="skill" name="skill">
<button id="ajou" name="ajou">Valide</button>
<br><br>
<div name="skills" id="skills"><p>hello</p> </div>
To be specific, when I click on the button Valid the text I entered in the input is add to my <div> but when I want to delete it I can't, only <p>hello</p> will remove it when I click on it.
Slight change to your event handler to give it scope:
$('#skills').on('click', 'p', function(){
$(this).remove();
});
This allows the event to be bound to the skills and thus allow all paragraphs (p) to be removed from within that scope. Binding to the p element only binds to the currently existing paragraphs (anywhere in the document) and not those added.
Edited to full sample and to only remove <p> elements when clicked on. Works for both static and dynamic <p> elements.
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<input type="text" id="skill" name="skill">
<button id="ajou" name="ajou">Valide</button>
<br><br>
<div name="skills" id="skills"><p>hello</p> </div>
JAVASCRIPT:
$('#ajou').click(function(){
alert( $('#skill').val());
$('#skills').append('<p>'+$('#skill').val()+'</p>');
});
$(document).on('click', '#skills p', function(events){
events.target.remove();
});
The latter is to bind the removal function to the parent element (#skills) simply because the children will be dynamically added later, so could not be bound beforehand. Once you catch the click on the parent it is possible to remove the clicked child <p> (targeted element).
$('div', {
id: 'foo',
name: 'anything',
title: 'adding these attributes is not necessary',
text: 'Waow, I am one sexy p tag'
}).appendTo($('.myDiv'));
Related
I have a page in which I have MCQ Options which looks like this:
This is the HTML Code for the options parts till now:
<div v-for="(option, index) in optionsForFrontend">
<div class="option">
<div class="radio-check-item">
<input type="radio"
name="question"
:value="index"
v-model="picked"
v-if="question.metadata.choices === 'Single'">
<input type="checkbox"
name="question"
:value="index"
v-model="picked"
v-if="question.metadata.choices === 'Multiple'">
</div>
<div class="divider">
</div>
<div class="content-item">
<vue-markdown :source="option.option"></vue-markdown>
</div>
</div>
</div>
I want to select the options by clicking on the option content. So I put a :click="functionToSelectOption" on the outer div ("option") containing checkbox and option content.
The problem is when I select the checkbox, it gets selected and the function "functionToSelectOption" gets called as well since the checkbox is inside the "option" div.
I want to be able to detect a click inside the "option" div but outside radio/checkbox div so I can call the function to toggle the option.
I mostly found similar questions under jquery tags and nothing with VueJS.
I would avoid event.stopPropagation(). All kinds of things might be listening higher up in the tree. For instance, you might want an onclick on the window to close a modal dialog if the user clicks outside the dialog. The much less radical way to do this is to look at event.target. This jsfiddle tests (event.target == event.currentTarget) so it only reacts to clicks on the parent div.
Markup
<div id="ctr">
<div v-for="(option,index) in options"
style="margin:10px;padding:10px;border:solid;border-radius:4px"
#click="parent"
>
<input type="checkbox" :name="'invidiousChoice' + index" #click='child'> {{option.label}}
</div>
</div>
JS
var vm = new Vue({
el:"#ctr",
data : {
options:[{label:'terrible option'},{label:'disastorous option'}]
},
methods: {
parent: function(event) {
if(event.target == event.currentTarget)
alert( 'parent clicked');
}
}
})
You can use event.stopPropagation() in child element.
Here is working JSFiddle Solution: Link
HTML
<div id="app">
<div #click="parent">
Parent
<div>
<input type="checkbox" #click="child">
</div>
</div>
{{message}}
JS
new Vue({
el: '#app',
data: {
message: ''
},
methods: {
parent: function() {
this.message = 'parent clicked';
},
child: function() {
event.stopPropagation()
}
}
});
I want to select a div using its class, but there are other divs with the same class and with the same buttons that trigger my function, so I only want to select the class where $(this) is in.
I tried .parent, .child, .contains, .find but I didn't figure it out...
$(".btt_class").click(function() {
// I know this is wrong, but to give an idea of what I need
$(".div_class").has(this).append("You cliked here");
});
<div class="div_class">
<input class="btt_class" type="button" value="Click me" />
</div>
<div class="div_class">
<input class="btt_class" type="button" value="Click me" />
</div>
If I understand your request correctly, your snippet does just what you described: selecting the div, the currently clicked button is in and appending some text to it:
Pleas check out https://jsfiddle.net/4qwy605p/
$(".btt_class").click(function() {
$(".div_class").has(this).append("You cliked here");
});
<div class="div_class">
<input class="btt_class" type="button" value="Click me" />
</div>
<div class="div_class">
<input class="btt_class" type="button" value="Click me" />
</div>
It works as requested in the fiddle.
Is it possible you just forgot to load jQuery in your snippet?
this should do the trick: (OOPS, edited to include finding the closest one.)
$(".btt_class").on("click",function(){
myDiv = $(this).parent().closest('div.div_class');
myDiv.append("You clicked here");
});
To capture the element of the button being clicked you can do this:
$(".btt_class").click(function() {
$this = $(this); // captures the input element
$div_class_elem = $this.parent(); // goes up one level/element to capture the div element
$div_class_elem.append("You clicked here"); // append this text to the end of the div element
});
Use .closest() to traverse up the DOM tree up to the specified selector. This should do the trick:
$(this).parent().closest('div').append("You clicked here!")
I'm not sure how to get the correct div to update and the correct link to click. I don't think I'm understanding the property usage for parent, sibling, find, prev, next, etc.
I'm submitting the form with AJAX and need to update the paragraph tag with class 'record-info' and click the link with class 'cancelas'.
The AJAX:
$('form').on('submit', function(e){
if($(this).attr('id') == 'editdelete'){
var thisform = $(this);
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function() {
var replaceText = thisform.find('input[name="extraedit"]').val();
console.log(thisform.parent().find('.record-info').html());
thisform.parent().find('.record-info').html(replaceText);
thisform.parent().find('.cancelas').click();
}
});
e.preventDefault();
}
});
replaceText displays the correct info in the console if I console.log it, but when I try to get the content of the 'record-info' paragraph, it displays as undefined. I've tried .parent().find(), .siblings(), .next(), .prev() and everything in between.
Here is the HTML structure:
<div class="catname record">
<p class="record-info">Info is here</p>
<p class="editmain">Edit</p>
<p class="markmain">Mark</p>
<form class="markas">FORM IS HERE</form>
<div class="editas">
<div>
<form action="edit-delete.php" id="editdelete" method="post">
<input name="extraedit" type="text">
</form>
<form action="edit-delete.php" id="editdelete" method="post">
FORM CONTENT
</form>
</div>
</div>
<p class="cancelas">Cancel</p>
</div>
.record-info is not a sibling of your forms, so just getting the parent and finding within that won't work.
Try closest(), which will traverse up the DOM tree until it finds a match (where parent only traverses one level, to the parent):
thisform.closest('.record').find('.record-info').html(replaceText);
The same goes for triggering your click:
thisform.closest('.record').find('.cancelas').click();
Note: I've used .record in closest() here because I'm assuming it is the common class across your 'records'. .closest('.catname') would work just as well in this case.
JSFiddle
I have about 50 p tags and next to these are again 50 divs. on click of each p tag, its div should be shown and the rest hidden. How do i acheive this. I can use something like below:
$(function() {
$('.p1').click(function(){
$('.div1').show();
$('.div2','.div3','.div4','.div5','.div6',.........,'.div50').hide()
})
$('.p2').click(function(){
$('.div2').show();
$('.div1','.div3','.div4','.div5','.div6',.........,'.div50').hide()
})
//////////////
//////
})
but as you see that this is not an effiecient solution. I am also not sure how the jquery each can be leveraged here or how can this implementation be done using arrays. Can somebody point me in the right direction. I think we should use a function and pass that no. as a parameter, but I dont know how to use custom functions in jquery.
UPDATE:
This is what I have done
$(function() {
$('.p1').click(function() {
$('.div').hide();
$('.d1').show();
})
})
I have added the class div to all of my 50 divs and I am showing d1 on click of p1. Now how do I replace 1 for each instance till 50.
I would have a common class to all div and p so that the binding the handler and the hide can be simple. And for the div, I would associate a data-tag to each p to link each p tag to div
<p class="p1 pclass" data-showdiv="div1">
...
</p>
<p class="p2 pclass" data-showdiv="div2">
..
<div class="mydiv div1" ..>
..
</div>
<div class="mydiv div2" ..>
..
</div>
And the script would be,
$(function() {
$('.pclass').click(function(){
$('.mydiv').hide();
$('.' + $(this).data('showdiv')).show();
});
});
As Jason told,
Use this
$('p').click(function() {
$('div').hide();
$(this).next('div').show();
});
If the div is next to each paragraph.
But, if there's an element between p and div, it wont work.
For you problem, you can do,
$('p').click(function() {
$('div').hide();
var divClass = $(this).attr("class").replace('p','div');
$('.' + divClass).show();
});
provided you have only p1, p2 .... in paragrah classes ;)
Update
See this fiddle
Notice , we have <br> tags between <p> and <div> as you wanted.
Assuming your HTML structure is
<p>Some text</p>
<div>More text to hide and show</div>
<p>Some text</p>
<div>More text to hide and show</div>
<p>Some text</p>
<div>More text to hide and show</div>
....
Use the following in your $(function(){}); method:
$('p').click(function() {
$('div').hide();
$(this).next('div').show();
});
var dvs = ['.div1','.div2','.div3','.div4','.div5','.div6',.........,'.div50'];
$('p').click(function() {
var index = parseInt(this.className.replace('p','')) - 1;
$(dvs[index]).show();
$(dvs.join(', ')).not(dvs[index]).hide();
});
The jQuery click event will automatically be registered on all elements that match the selector, so you shouldn't have to use the each() method. I would suggest having two CSS classes to distinguish between elements that have this toggling behaviour and elements that are primary (i.e. should be shown when their parent is clicked).
The markup:
<body>
<p class="togglable">
<div class="primary">
This is the primary div that will be shown when our parent is clicked.
</div>
<div>Regular div child</div>
<p>Nested paragraph</p>
<ul>
<li>A list perhaps</li>
</ul>
</p>
<p class="togglable">
<div class="primary">
This is the primary div that will be shown when our parent is clicked.
</div>
<div>Regular div child</div>
<p>Nested paragraph</p>
<ul>
<li>A list perhaps</li>
</ul>
</p>
<p>This is a normal paragraph</p>
</body>
The code:
$(function () {
$('.togglable').click(function () {
// hide all our children
$(this).children().hide();
// now only show our primary chlid
// NOTE: we pass 'this' as the second argument
// so that the selector will only apply to the
// children of the element that was clicked
// (i.e. we are providing a custom context for the selector).
$('.primary', this).show();
// You could even use the position of the child as well:
// $(this).children().first().show();
// This will show the first child element.
});
});
In this example all elements with the class togglable will show their primary child element when clicked and hide all other child elements.
I am trying to remove some elements using a link. The elements that I am trying to remove are in a link's parent div, but i cannot seem to remove them.
Here is the HTML:
<div class="QR-answer-holder">
<label class="QR-answer-label">Enter an answer:</label>
<input class="QR-answer-input textbox" type="text" name="answer" />
</div>
<a class="new-answer new-qr-answer-space" href="javascript:void(0)">New answer space</a> |
<a class="remove-answer remove-qr-answer-space" href="javascript:void(0)">Remove Answer Space</a>
Here is the JQuery:
$remove_qr_answer = $(".remove-qr-answer-space");
$remove_qr_answer.live("click", function() {
$(this).parent.$(".QR-answer-holder").$(".QR-answer-label").remove();
$(this).parent.$(".QR-answer-holder").$(".QR-answer-input").remove();
});
Is there anyway to make it so the remove button removes the label and input closest to the end of the div? (or does it do that automatically)?
You're accessing the .parent() node from that anchor .new-qr-answer-space.
Infact, you need to get the .sibling(), since the div.QR-answer-holder is not the parent node:
$remove_qr_answer = $(".remove-qr-answer-space");
$remove_qr_answer.live("click", function() {
$(this).siblings(".QR-answer-holder").find(".QR-answer-label:last, .QR-answer-input:last").remove();
});
try
$remove_qr_answer = $(".remove-qr-answer-space");
$remove_qr_answer.live("click", function() {
$(this).parent().find($(".QR-answer-holder").remove();
});
and it should remove the lable and input as those are inside the placeholder
see siblings:
$(this).siblings('.QR-answer-holder .QR-answer-label').remove();
this would remove the elements '.QR-answer-holder .QR-answer-label' from the same dom node as this.
Try using this
HTML:
<div class="QR-answer-holder">
<label class="QR-answer-label">Enter an answer:</label>
<input class="QR-answer-input textbox" type="text" name="answer" />
</div>
<a class="new-answer new-qr-answer-space" href="#">New answer space</a> |
<a class="remove-answer remove-qr-answer-space" href="#">Remove Answer Space</a>
JavaScript:
$remove_qr_answer = $(".remove-qr-answer-space");
$remove_qr_answer.live("click", function(e) {
e.preventDefault();
$(this).siblings(".QR-answer-holder").find(".QR-answer-label,.QR-answer-input").remove();
});
parent is a method, not a property. There is no $ method in the jQuery object, you use the find method to locate children:
$(this).parent().find(".QR-answer-holder .QR-answer-label").remove();
$(this).parent().find(".QR-answer-holder .QR-answer-input").remove();
Edit:
As you actually want to get the closest sibling before the link, you should use the prev method instead:
$(this).prev().find(".QR-answer-holder .QR-answer-label").remove();
$(this).prev().find(".QR-answer-holder .QR-answer-input").remove();
Or if you want to remove all elements in the div, simply:
$(this).prev().empty();