I want to get a text from a textarea after clicking on button that is next to the textarea.
The problem is that I will have many textareas and every button must returns the text of the textarea that corresponds to it.
This is my code
function btnmodif(){
var mod = $(this).prev().val();
alert(mod);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="list-item-edit">
<textarea class="list_input">eggs</textarea>
<button class="btn btn-modify-item" onClick="btnmodif()">get text</button>
</div>
<div class="list-item-edit">
<textarea class="list_input">water</textarea>
<button class="btn btn-modify-item" onClick="btnmodif()">get text</button>
</div>
You have to pass object clicked to btnmodif function.
<button class="btn btn-modify-item" onClick="btnmodif(this)">get text</button>
JS
function btnmodif(button){
var mod = $(button).prev().val();
alert(mod);
};
Also, you should use .prev function.
Read more about .prev() function, here.
function btnmodif(button){
var mod = $(button).prev().val();
alert(mod);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="list-item-edit">
<textarea class="list_input">eggs</textarea>
<button class="btn btn-modify-item" onClick="btnmodif(this)">get text</button>
</div>
<div class="list-item-edit">
<textarea class="list_input">water</textarea>
<button class="btn btn-modify-item" onClick="btnmodif(this)">get text</button>
</div>
Firstly, you need to pass the clicked element as context to the function:
onClick="btnmodif(this)"
...
function btnmodif(button){
Second, if the HTML structure will remain the same (i.e. the textarea is always going to be the element immediately before the button), then you can use prev()
var mod = $(button).prev('textarea').val();
https://api.jquery.com/prev/
If that structure isn't guaranteed to be maintained, then .siblings() gives you a bit more flexibility, as it searches through all the elements at the same hierarchical level in the DOM to find what you want:
var mod = $(button).siblings('textarea').val();
https://api.jquery.com/siblings/
Here is what are you looking for.
Add this as parameter to your button.onclick
Thanks to jQuery:
Using $(element).parent(), you get your div element.
Using $(element).parent().find('.list_input'), you get your textarea element.
Using $(element).parent().find('.list_input').text() gives you the value of the textarea "related to" the clicked button.
function btnmodif(element){
var result = $(element).parent().find('.list_input').text();
alert(result);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="list-item-edit">
<textarea class="list_input">eggs</textarea>
<button class="btn btn-modify-item" onClick="btnmodif(this)">get text</button>
</div>
<div class="list-item-edit">
<textarea class="list_input">water</textarea>
<button class="btn btn-modify-item" onClick="btnmodif(this)">get text</button>
</div>
You're missing the this from the inline handler specification:
https://jsfiddle.net/3mvod6ux/
Use siblings with a selector to get the textarea's value that belong to the same block of the button clicked.
function btnmodif(button){
var mod = $(button).siblings("textarea").val();
alert(mod);
};
Another way to do this task .
Instead to use HTML event attribute this is better approach.
var btnModifyItem = $('.btn-modify-item');
btnModifyItem.click(function(){
var mod = $(this).prev().val();
alert(mod);
})
This way you can get the parent of button (and textarea) and then can get the text from child textarea:
$('button').on('click', function () {
console.log(($(this).parent().find("textarea").text()));
});
Related
I'm encountering a typical situation while accessing the innerHTML property using jQuery. I've fetched the target button using the jQuery attribute selector.
Below is the snippet of jQuery attribute selector.
jQuery('button[type="button"][class="btn btn-primary"]').each(function () {
var btn = jQuery(this);
console.log(btn);
if (btn[0].innerHTML === "OK") {
console.log("ok");
jQuery(this).click();
}
});
Following is the screenshot of the console log of the target button. It's innerHTML property is set to OK.
Following is the screenshot of the value of the innerHTML while debugging the target button object. In this case the value is "".
Ideally, the values of the innerHTML should be the same for both the cases.
EDIT
Why does this behavior differ that the ideal one? For both of the cases, the value of the innerHTML should be the same.
Also, there were multiple buttons. I have taken screenshots of different buttons. Thus their ID's are different. But still, the behavior is same.
Try something like this.
function SomeEvent($ele) {
alert($ele.html());
return false;
}
function invokeBtnEvents() {
$("[data-action=some-event]").off(); // clear old events
$("[data-action=some-event]").on("click", function() {
var $this = $(this);
return SomeEvent($this);
}) // define event(s)
return false;
}
$(document).ready(function() {
invokeBtnEvents();
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-12">
<br />
<button data-action="some-event" class="btn btn-primary">Button 1</button>
<button data-action="some-event" class="btn btn-primary">Button 2</button>
<button data-action="some-event" class="btn btn-primary">Button 3</button>
<button data-action="some-event" class="btn btn-primary">Button 4</button>
</div>
</div>
</div>
Your issue
What you are doing that I think is your main issue is the $.each() method.
Store the buttons in a variable,
let $button = $("button"); // this returns an array of all the buttons on the DOM
You can then use the $.each() method to get the clicked element
$.each($button, function(index, btn){
const $this = $(btn);
$this.off();
$this.click(function(){someEvent($this)});
});
I would not invoke button clicks like this because every time you click a button, this each loop gets ran. It will then send all of the buttons to that action unless you parse by an ID or something (you are using the innerText).
If you use the code in my snippet, only the clicked button will be triggered.
An alternative approach to my first snippet is using something like a dispatcher.
function DoActionOneClick($ele){
alert("Action 1 " + $ele.html());
}
function DoDefaultClick($ele){
alert("Default Action " + $ele.html());
}
function DispatchEvent(action, $ele){
switch(action){
case "some-event-1":
DoActionOneClick($ele);
break;
default:
DoDefaultClick($ele);
break;
}
}
function invokeActions(){
$("[data-action]").off();
$("[data-action]").on("click", function(){
// get this
var $this = $(this);
// get action
var action = $this.data().action;
DispatchEvent(action, $this);
});
}
$(document).ready(function(){
invokeActions();
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-12">
<br />
<button data-action="some-event-1" class="btn btn-primary">Button 1</button>
<button data-action="some-event-2" class="btn btn-primary">Button 2</button>
<button data-action="some-event-2" class="btn btn-primary">Button 3</button>
<button data-action="some-event-2" class="btn btn-primary">Button 4</button>
</div>
</div>
</div>
$(document).ready(function(){
$("button").click(function(){
$("#answer").toggle(1000);
});
});
this only works for the IDs "answer" and "button", the challenge for me its getting multiple pairs of these IDs (answer1 - button1, answer2 - button2, and so on) to work with this single function
You haven't included the relevant HTML so I can only guess/assume what it might look like in my demo/example.
For multiple elements it is best to use a class to group them.
$(document).ready(function() {
$(".answerTog").click(function() {
$(this).prev('.answer').toggle(1000);
});
});
.Question {
display: block;
margin-bottom: 5px;
}
.answer {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Question">
<input type="text" placeholder="Question One" />
<span class="answer">Question One Answer.</span>
<button class="answerTog">See Answer</button>
</div>
<div class="Question">
<input type="text" placeholder="Question Two" />
<span class="answer">Question Two Answer.</span>
<button class="answerTog">See Answer</button>
</div>
<div class="Question">
<input type="text" placeholder="Question Three" />
<span class="answer">Question Three Answer.</span>
<button class="answerTog">See Answer</button>
</div>
If your button is before the answer then you can simply use
$(this).next('.answer').toggle(1000);
$(this) will target the specific element used to trigger the function call, in this instance the button being clicked.
.prev('.answer') will target the previous element with the class name of answer
.next('.answer') will target the next element with the class name of answer
JsFiddle Demo
If you have any questions about the source code above please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!
You are currently using an ID property to call that button ($('#')) You want to call them by classes.
IDs should be unique and only used in 1 DOM element.
Trying to use ID the script will only pick the 1st element it comes across; and the code will only work for that one button.
With classes you create an Object for all of your elements, with jQuery you just have to call the element by its class, and run the code normally - I note this because in JS you would have to add the index to the element call.
For example:
<canvas id="main"></canvas>
<div class="elem"></div>
<div class="elem"></div>
<div class="elem"></div>
<script>
var canvas = $('#main'), // return 1 element
elements = $('.elem'); // return 3 elements
</script>
So for anything that involves multiple elements you must call them by class or tag name.
In vanilla JS you would look at something like this:
<script>
var elem = document.querySelectorAll('.elem');
console.log(elem[0]);
</script>
So, your code would then just need to call those elements by class; and you can set custom classes for different purposes.
$(document).ready(function() {
var btns = $('.btn');
btns.click(function() {
btns.toggle(1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn">Button</button>
<button class="btn">Button</button>
<button class="btn">Button</button>
<button class="btn">Button</button>
<button class="btn">Button</button>
I have some sort of calculator, and I need to insert .num-pad_number.html() into my input. Is that correct way to do this:
$("#num-pad").on("click", ".num-pad_number", function (event) {
$("#calc-input").val($("#calc-input").val() + $(this).html());
});
Or it may be more convinient and correct way? Cuz I have some bug with that solution. After some manipulations with websockets, "calculator" starts to duplicate every number, for example I need "5" but it insert "55".
Slightly modified. Using .text() instead of .html(). Shorter event function. Working example below:
$('#num_pad .num-pad_number').click(function() {
$("#calc-input").val($("#calc-input").val() + $(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="calc-input" type="text"/>
<div id="num_pad">
<button class="num-pad_number">1</button>
<button class="num-pad_number">2</button>
<button class="num-pad_number">3</button>
<button class="num-pad_number">4</button>
<button class="num-pad_number">5</button>
<button class="num-pad_number">6</button>
<button class="num-pad_number">7</button>
<button class="num-pad_number">8</button>
<button class="num-pad_number">9</button>
</div>
How do I reference a UIkit Component in Javascript? I made a small example of my problem:
This is the HTML:
<div class="uk-panel">
<div id="myRadios" data-uk-button-radio>
<button class="uk-button">Option1</button>
<button class="uk-button">Option2</button>
<button class="uk-button">Option3</button>
</div>
</div>
<br/>
<button class="uk-button" onclick="check()">Check Selection</button>
And here is the Javascript part:
function check() {
var selected = $('#myRadios').getSelected();
var selected2 = $('#myRadios').uk('buttonRadio').getSelected();
// getSelected() is not defined in both!
}
I also created this as a plunker: http://plnkr.co/edit/U4ELL78YSsBbBHiwGnOQ
Thanks for your help!
UIkit seems to only toggle buttons(I don't see any api inside docs), and adds class uk-active to selected buttons. So maybe something like this:
$('#myRadios button').on('click', function() {
var selectedValue = $(this).text();
console.log(selectedValue);
});
I'm new in JavaScript and I took an app here to learn how to use the language.
So, In my index.html I have this code here:
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore">Reset</button>
<script type="text/javascript">
function reset() {
localStorage.setItem('total_win', 0);
localStorage.setItem('total_lose', 0);
}
</script>
</div>
and this as footer:
`<div id="scores" class="ui-grid-b">
<div class="ui-block-a">Tries left:<span id="tries_left">4</span></div>
<div class="ui-block-b">Total win:<span id="total_win">0</span></div>
<div class="ui-block-c">Total lost:<span id="total_lose">0</span></div>
</div>`
What I'm basically trying to do is just reset the score to zero. But It's not working...
I tried to put some alert() inside reset() function but didn't work also.
Does someone has a clue why this is happening?
Thanks for helping!
Use onclick property:
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore" onclick="reset()">Reset</button>
<script type="text/javascript">
function reset() {
localStorage.setItem('total_win', 0);
localStorage.setItem('total_lose', 0);
}
</script>
</div>
You are declaring the function but not calling it anywhere. So you need to call the function at onclick event of button.
You should add an event listener for the click event.
Because of your comment, you can change the DOM by changing the inner HTML, see below snippet and code:
document.getElementById('resetscore').addEventListener('click',function() {
//localStorage.setItem('total_win', 0);
//localStorage.setItem('total_lose', 0);
document.getElementById('total_win').innerHTML = 0;
document.getElementById('total_lose').innerHTML = 0;
});
document.getElementById('win').addEventListener('click',function(){
var a = parseFloat(document.getElementById('total_win').innerHTML);
document.getElementById('total_win').innerHTML = (a+1).toFixed(0);
});
document.getElementById('loss').addEventListener('click',function(){
var b = parseFloat(document.getElementById('total_lose').innerHTML);
document.getElementById('total_lose').innerHTML = (b+1).toFixed(0);
});
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore">Reset</button>
<button type="button" id="win">+1 Win</button>
<button type="button" id="loss">+1 Loss</button>
</div>
<div id="scores" class="ui-grid-b">
<div class="ui-block-a">Tries left:<span id="tries_left">4</span></div>
<div class="ui-block-b">Total win:<span id="total_win">0</span></div>
<div class="ui-block-c">Total lost:<span id="total_lose">0</span></div>
</div>
your script tag can't be inside a div. You need to move all your javascript to the end of your body, right before its closing tag, after all the html
Just add this:
<button type="button" onclick="reset()" id="resetscore">
You need to tell which one of your functions to use, notice the onclick, it does just that, so reset executes on click
Your button needs to call reset
<button type="button" id="resetscore" onclick="reset()">Reset</button>