Find Parent Sibling First Child's First Child using Jquery - javascript

I'm trying to Use a combination of JS and Jquery here to select the input text (a few elements previous), when the button is clicked.
I know how to do this just using JS but i want to understand how to do this using jQuery. I get the error message in console: TypeError: ele.setSelectionRange is not a function. Which I take it means that it is not defining the Input Value the way I need it to.
I'm not using ID or Class here to identify the input.
Can someone help me here? Thanks
JS
$(document).ready(function () {
$('.jimmy').click(function(e){
e.preventDefault;
jimsFunction(this);
});
});
function jimsFunction(input) {
let ele = $(input).parent().siblings(':first-child').children();
ele.select();
ele.setSelectionRange(0, 99999);
navigator.clipboard.writeText(ele.value);
alert("Copied: " + ele.value);
}
HTML
<div class="colbody">
<div>
<input type="text" value="www.brave.com" readonly>
</div>
<div>
View
</div>
<div>
<button type="button" class="jimmy">Copy URL</button>
</div>
</div>

setSelectionRange(0, 99999) is not a method on jQuery object. Use it on DOM element.
So try: [0]
Example:
$('.jimmy').click(function(e) {
e.preventDefault;
jimsFunction(this);
});
function jimsFunction(input) {
let ele = $(input).parent().siblings(':first-child').children();
ele[0].select();
ele[0].setSelectionRange(0, 99999);
navigator.clipboard.writeText(ele[0].value);
alert("Copied: " + ele[0].value);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="colbody">
<div>
<input type="text" value="www.brave.com" readonly>
</div>
<div>
View
</div>
<div>
<button type="button" class="jimmy">Copy URL</button>
</div>
</div>

Related

How to increase ID while copying a tag in javascript

I have a form and in my form there is a plus button for adding a div and at last I will send a list of that div to my controller.
$(“#addDiv”).click(function() {
$(“#myForm div# section_0).clone().appendTo(“#myForm”);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id=“myForm”>
<div id=“section_0”>
//some tags here
</div>
<button id=“addDiv” class=“btn btn-primary”>add</add>
</form>
There is not any problem in copying that div but I need to append a new id for that div and be increased by one.
If anyone can help I would appreciate
Set a global variable globalSectionId to increment at each click and replace the attribute id each time you clone()
globalSectionId = 0;
$("#addDiv").click(function (){
$("#myForm div#section_0").clone().attr({id:`section_${++globalSectionId}`}).appendTo("#myForm");
// clone(). and set the new id with the .attr() - Thx #Phil
});
I made a JSFiddle working: https://jsfiddle.net/4efkhdba/
globalSectionId = 0;
$("#addDiv").click(function (){
$("#myForm div#section_0").clone().attr({id:`section_${++globalSectionId}`}).appendTo("#myForm");
// clone(). and set the new id with the .attr() - Thx #Phil
console.log('the new id:'+globalSectionId)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myForm">
<div id="section_0">
CLONE DIV!
</div>
<button type="button" id="addDiv" class="btn btn-primary">add</add>
</div>
You better create a div with id boilerplate and then use it for cloning. Once you append the clone then iterate through the whole div list and add the id's.
<div id="boilerplate" class="tag">
// some tags here
<div>
$("#addDiv").on("click", function() {
$("div#boilerplate").clone().appendTo("#myForm");
$("#myForm").find("div.tag").each(function(i) {
$(this).attr("id", "section_" + i);
});
});
Try this.
Here I have declared one variable which helps us to update id dynamically.
var id=1;
$("#addDiv").click(function() {
var $div=$("#myForm div:last")
var klon=$div.clone().prop('id','section_'+id++);
$div.after(klon);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<div id="section_0">
//some tags here
</div>
</form>
<button id="addDiv" class="btn btn-primary">add</button>
You can try this code here:
Not needed any loop just use document find item length because item length is given integer number and our id start at 0. so when item one then it returns 1 and we create new item id with last change one (1).
$("#addDiv").on('click',function(e){
e.preventDefault();
$('#section_0').append('<div id="section_'+$(document).find('.item').length+'" class="item"> Section '+$(document).find('.item').length+'</div>');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<div class="item" id="section_0">
//some tags here
</div>
<button id="addDiv" class="btn btn-primary">add</div>
</form>
==== Thanks ====

JQuery Detect Which File Upload Button Clicked [duplicate]

How to detect which dynamic button is clicked?
Note: The #dCalc Element is added dynamically...
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<input id="firstNumber" type="text" maxlength="3" />
<input id="secondNumber" type="text" maxlength="3" />
<input id="btn1" type="button" value="Add" />
<input id="btn2" type="button" value="Subtract" />
<input id="btn3" type="button" value="Multiply" />
<input id="btn4" type="button" value="Divide" />
</div>
</div>
$("input").click(function(e){
var idClicked = e.target.id;
});
$(function() {
$('input[type="button"]').click(function() { alert('You clicked button with ID:' + this.id); });
});
Since the block is added dynamically you could try:
jQuery( document).delegate( "#dCalc input[type='button']", "click",
function(e){
var inputId = this.id;
console.log( inputId );
}
);
demo http://jsfiddle.net/yDNWc/
jQuery can be bound to an individual input/button, or to all of the buttons in your form. Once a button is clicked, it will return the object of that button clicked. From there you can check attributes such as value...
$('#dCalc input[type="button"]').click(function(e) {
// 'this' Returns the button clicked:
// <input id="btn1" type="button" value="Add">
// You can bling this to get the jQuery object of the button clicked
// e.g.: $(this).attr('id'); to get the ID: #btn1
console.log(this);
// Returns the click event object of the button clicked.
console.log(e);
});
Detect event on dynamically created elements
Two examples, jQuery and vanilla JavaScript ahead:
jQuery
Use the .on() method with delegated events, which follows this syntax:
$("staticParentSelector").on("eventName", "dynamicChildSelector", handlerFn);
Example:
// Assign event listeners to dynamic child elements
// Will work for either existent elements or inserted in the future
$("#dBlock").on("click", '[type="button"]', (evt) => {
const staticParent = evt.delegateTarget; // This is #dBlock
const dynamicChild = evt.currentTarget; // This is the dynamic child
console.log(`Static Parent ID is: ${staticParent.id}`)
console.log(`Dynamic child ID is: ${dynamicChild.id}`)
});
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<button type="button" id="btn1">Add</button>
<button type="button" id="btn2">Subtract</button>
<button type="button" id="btn3">Multiply</button>
<button type="button" id="btn4">Divide</button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
JavaScript
The same in vanilla JavaScript can be achieved like the following, with the difference in that JS has no notion of delegateTarget (which is a jQuery property on their proprietary Event object) therefore the slight modification:
// Assign event listeners to dynamic child elements
// Will work for either existent elements or inserted in the future
document.querySelector("#dBlock").addEventListener("click", (evt) => {
const staticParent = evt.currentTarget; // This is #dBlock
const dynamicChild = evt.target.closest('[type="button"]'); // This is the dynamic child
if (!dynamicChild) return; // Do nothing (no designated dynamic child is clicked)
console.log(`Static Parent ID is: ${staticParent.id}`)
console.log(`Dynamic child ID is: ${dynamicChild.id}`)
});
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<button type="button" id="btn1">Add</button>
<button type="button" id="btn2">Subtract</button>
<button type="button" id="btn3">Multiply</button>
<button type="button" id="btn4">Divide</button>
</div>
</div>
as you can see neither of the above implementations stick solely on the Event.target Element per-se, for the reason that if we had i.e. an icon inside the buttons (like: <button id="add" type="button">Add <i class="icon-plus"></i></button>) and if a click landed on the icon directly, the Event.target would end up being the icon, not the Button Element - and we might miss to retrieve the needed data, like the specific button ID etc, resulting in a broken app logic.

check value of input field

I have structure like this. On button click jquery code make border of input red if field is empty. Everything works fine with first row. At others row border become red after button click even if i put valid value.
$('.btn-submit').click(function(){
var value = $(':input').val();
if(!value.length) {
$(this).parents('.row').find(':input').css('border-color','#f00');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='row'>
<input>
<button class='btn-submit'>Check</button>
</div>
<div class='row'>
<input>
<button class='btn-submit'>Check</button>
</div>
<div class='row'>
<input>
<button class='btn-submit'>Check</button>
</div>
Change you JS-Code:
$('.btn-submit').click(function(){
var value = $(this).parent().find('input').val();
if(!value.length) {
$(this).parents('.row').find(':input').css('border-color','#f00');
}
});
Your Issue:
You select all <inputs/> instead of the closest.
When any button is clicked, it is checking the value of the first <input>.
Change this line:
var value = $(':input').val();
To this:
var value = $(this).prev(":input").val();
This should select the <input> element directly before the button.
Another tip: You seem to try to find the child input of the parent using jQuery. Instead, you can find the sibling, using something like prev() (which will work in your case).
Try this:
$('.btn-submit').click(function(){
var value = $(this).parent().find("input").val();
if(!value.length) {
$(this).parent().find(':input').css('border-color','#f00');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='row'>
<input>
<button class='btn-submit'></button>
</div>
<div class='row'>
<input>
<button class='btn-submit'></button>
</div>
<div class='row'>
<input>
<button class='btn-submit'></button>
</div>
Your problem is that you are looking at all the inputs not just the sibling of the button.
Try this javascript instead:
$('.btn-submit').click(function(){
var value = $(this).parent().find('input').val();
if(!value.length) {
$(this).parents('.row').find(':input').css('border-color','#f00');
}
});
Here is the fiddle

html get div tag in many levels

I got class required on div tag, and I want to remove it change function of text field, but I can't get to that div level, please help me to reach this.parent.parent.closest('div')
<div class='required'>
<div>
<div>
<input type='text' value='123' onchange(removeRequired(this, this.parent.parent.closest('div')))/>
</div>
</div>
</div>
<script type='text/javascript'>
function removeRequired(elm1, elm2){
if ($(elm1).val()) {
$(elm2).removeClass('required');
}
}
</script>
It seems that what you want is to add/remove the required class based on whether the input is empty or not.
$('.required').on('change', 'input', function(event) {
// add or remove required class
$(event.delegateTarget)
.toggleClass('required', this.value.length === 0);
});
It will work with the following HTML:
<div class='required'>
<div>
<div>
<input type='text' value='123'/>
</div>
</div>
</div>
It sets up event delegation on the outermost <div> elements and then sets or removes the required class based on the input value.
Demo
You dont have to mess up with javascript and jquery. You can bind the change event with jquery like this,
$(document).ready(function () {
$("input[type='text'] ").change(function () {
$(this).closest(".required").removeClass("required");
});
});
try this
$("input[type=text]").closest('div.required').removeClass("required");
onchange function be
$("input[type='text']").change(function(){
$(this).closest("div.required").removeClass("required");
});
or
$("input[type='text']").change(function(){
$(this).parents("div.required").removeClass("required");
});
Why not easily working with id?
<div id="input-wrapper" class='required'>
<div>
<div>
<input type='text' value='123' onchange="removeRequired(this, $('#input-wrapper'))"/>
</div>
</div>
</div>
<script type='text/javascript'>
function removeRequired(elm1, elm2){
if ($(elm1).val()) {
$(elm2).removeClass('required');
}
}
</script>
By the way, if you want to reach the div class='required' with parent, you need 3 levels! Althougth the use of closest() is by far a better answer.
You can try:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
</head>
<div class='required'>
<div>
<div>
<input type='text' value='123' onchange="removeRequired.call(this)"/>
</div>
</div>
</div>
<script type='text/javascript'>
function removeRequired(){
$(this).parent().parent().parent().removeClass('required');
}
</script>

How to select input content if there is only one error class

I want to check if there is only one div with an error class. And if so, I want to .select() the content of the input (that's in the in corresponding input class div).
How would I do such thing?
My attempt which does not work:
if($("div.addition").hasClass(".error").length === 0) {
(this).parent().find('input').select();
}
HTML
<form>
<div class="input">
<input type="text">
<div>
<div class="addition">Message message.</div>
</div>
</div>
<div class="input">
<input type="text">
<div>
<div class="addition">Message.</div>
</div>
<div class="input">
<!-- So in this case this input's content will be selected -->
<input type="text">
<div>
<div class="addition error">Error message.</div>
</div>
</div>
</form>
Here's a jsFiddle that should do it - I mentioned as a comment to your post that you're missing a </div> tag, that is fixed in the fiddle - without it, the jquery selector matches two inputs. Outline of the js:
if ($('div.error').length === 1) {
errorContent = $('div.error').parents('div.input').find('input').val();
alert(errorContent);
}
Here's a plain JavaScript implementation. No need to use jQuery unless you're already using it.
var errors = document.getElementsByClassName('error');
if(errors.length === 1){
//If there is one class with error
var content = errors[0].innerHTML;
} else{
//there is more than one error class.
}
I want to check if there is only one div with an error class.
if ($("div.error").length === 1) {
// Exactly one div with the class "error"
}
else {
// Zero or more than one
}
By using jQuery it can be done like:
$(document).ready(function(){
var div = $('.error');
if(div.length){
var val = div.parents('.input:first').find('input').val();
//val is the value of input
}
});

Categories

Resources