I have a lot buttons all over a site with a value (the text of the button) and each has, for example a bootstrap class of '.btn-default':
<input type="button" value="Clear" class="form-control input-sm btn-default" onclick="doingSomethingElseEtc();">
How might I use jQuery to get the value of the button and bind it to a title attribute to each button, so if you moused over the button, you'd get the default browser tooltip containing the string from the button value, etc..?
For example, just to get the gist of what I'm asking:
$('.btn-default').attr('title', $(".btn-default").val());
I'm trying to touch the code as little as possible, etc..
Thank you!
You can use each to iterate each button and set the titles.
$('.btn-default').each(function(i,obj){
$(obj).attr('title', $(obj).val());
});
No need for any arguments, or variables, or other whatzit. :-)
$('.btn-default').each(function () {
$(this).attr('title', $(this).val());
});
Demo
Your idea will work too, if you're adding a function to the attr like this:
$('.btn-default').attr('title', function() {
//console.log($(this).val(), $(this).text());
return $(this).val() || $(this).text();
});
This will add to each button with class btn-default the title attribute.
I think it's also good to get the text because your button could be defined with input value=".." or with <button>text</button>
Please have a look at the demo below and in this jsFiddle.
$('.btn-default').attr('title', function() {
//console.log($(this).val(), $(this).text());
return $(this).val() || $(this).text();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="Clear" class="form-control input-sm btn-default" onclick="doingSomethingElseEtc();">
<button class="btn-default">test1</button>
<button class="btn-default">test2</button>
When you read the value of a collection of elements, jQuery only returns the value of the first one in the set. So you need to iterate over all of them and set the title on each one.
$('.btn-default').each( function () {
var elem = $(this);
elem.attr('title', elem.val());
});
Downside to this is if there is a lot of elements, it will be slow. Also you need to do this on document ready.
Related
On my HTML I have buttons list and text input field. Input field is to add extra buttons to my buttons list.
On jQuery I have eventListener when one of these buttons with .choices is clicked console log its value.
It works fine without any errors. But when I add extra button to my list with same class (.choices) new button appears but it doesn't respond to my click.
Any suggestions?
<div class="buttons">
<button id="button0" class="choices">Running</button>
<button id="button1" class="choices">Yoga</button>
<button id="button2" class="choices">Karate</button>
</div>
JS
$("#add-button").click(function(){
var inputValue = $("#add-input").val();
var generatedId = "button" + healthyChoices.length;
healthyChoices.push(inputValue);
$("<button>").attr("id", generatedId).appendTo(".buttons");
$("#" + generatedId).attr("value", inputValue);
$("#" + generatedId).attr("class", "choices");
$("#" + generatedId).text(inputValue);
$("#add-input").val("");
});
$(".choices").click(function(){
var selectedGroup = $(this).val();
console.log(selectedGroup);
});
The .click method does not handle elements dynamically added to the DOM. You should be using the .on method (as indicated by dfsq's comment).
See this SO post: Difference between .on('click') vs .click()
A little frustrated here, somehow I can't make this work no matter what I try. I have a small form with 2 offsets, each containing a few checkboxes as the following:
<input type="checkbox" id="test1" /><label for="test1">
I need to make sure the user selects at least one of them in each offset in order to be able to click this button, otherwise it should be unclickable :)
<div class="offset6">
<a class="btn btn-warning" href="#openModal">CONTINUAR<span class="btn_caret"></a>
</span></button>
</div>
This should work for you:
//listen for changes to any checkbox so we can re-evaluate the button state
$("input[type='checkbox']").change(function(){
validateInput();
});
//checks to see if the button should be enabled or not
function validateInput(){
//get the count of checked items in each of the offsets
var offset3Count = $(".offset3").find("input[type='checkbox']:checked").length;
var offset8Count = $(".offset8").find("input[type='checkbox']:checked").length;
//set the disabled state of the button based on the offset counts
$(".btn").prop("disabled", offset3Count == 0 || offset8Count == 0);
}
//call the function on page load to ensure the button is initially disabled
validateInput();
Here is a working example (I had to change your HTML a bit as it was invalid)
If you need a specific .btn, as in the one in offset6, then use this line instead:
$(".offset6 .btn").prop("disabled", offset3Count == 0 || offset8Count == 0);
Here is the example
A quick recommendation: If you have unique elements then consider using an id attribute for them. For example:
<button id="btn6" ...>
With the following JQuery selector:
$("#btn6")...
Try
var chk = $(".offset3,.offset8").find('input[type="checkbox"]'); //cache your selector
chk.change(function () {
$('div.offset6 a.btn.btn-warning[href="#openModal"]').prop('disabled', chk.filter(':checked').length);
});
chk.filter(':checked').length get length of checked checboxes
$('.btn').prop('disabled', $('input[type="checkbox"]:checked').length);
Updated After OP's Comment
$('div.offset6 a.btn.btn-warning[href="#openModal"]').prop('disabled', $('input[type="checkbox"]:checked').length);
or add and id to than use # id-selector
So I have a page that I want to use to allow users to see what in currently in the database and edit them by clicking on the box.
I have a pretty hacky method that works for text imputs but for a drop down box or date selector completely falls apart.
my HTML
<td name='joineddate133'>
<input type='date'
id='joind133'
name='joinda133
value='2012-03-15'
class='toedit'
readonly='readonly'
onclick='enablejoindate(this.id)'
size='20' />
< /td>
The current Javascript
<script>
function enablejoindate(joindatid){
$(function(){
$("input:text[id="+ joindatid +"]").removeAttr("class");
$("input:text[id="+ joindatid +"]").removeAttr("readonly");
$("input:text[id="+ joindatid +"]").addClass("inlineditjoind");
});
}
</script>
The inlinedit class is used as a marker so the jquery can find it easily to post and the toedit class currently just hides the attributes.
Obviously this solution isn't great and I would like to try and work out a better way to maybe create an input on the double click function etc.
You could have all fields as readonly and hidden until focussed:
$("table").on("focus", "input, select", function(){
$(this)
.prop("readonly", false)
.removeClass("toedit");
});
$("table").on("blur", "input, select", function(){
$(this)
.prop("readonly", true)
.addClass("toedit")
.siblings("span").text($(this).val());
});
$("table").on("click", "td", function(){
$(this).children().focus();
});
DEMO (updated again)
You should take a look at X-editable.
<a
href="#"
id="joinda133"
data-type="date"
data-viewformat="dd.mm.yyyy"
data-pk="1"
data-placement="right"
data-original-title="Date you've joined"
>25.02.2013</a>
Since you are using jQuery, use a jQuery event. It's best to set readonly to false with the prop() method:
$('input[type=date]').on('click', function(){
$(this)
.removeClass("toedit")
.prop("readonly", false)
.addClass("inlineditjoind");
});
JSFiddle
Have a look to the DEMO JSFiddle
JS/JQUERY -
$("#joind133").on('click',function(){
$(this).removeProp("readonly")
.removeClass("toedit")
.addClass("inlineditjoind");
});
HTML -
<td name='joineddate133'>
<input type='date' id='joind133' name='joinda133' value='2012-03-15' class='toedit' readonly='readonly' size='20'/>
</td>
UPDATE ON REQUEST FOR MAKING IT GENERIC BINDING
$("input[type='date']").on('click',function(){
$(this).removeProp("readonly")
.removeClass("toedit")
.addClass("inlineditjoind");
});
Problem: Creating an Element on a button click then attaching a click event to the new element.
I've had this issue several times and I always seem to find a work around but never get to the root of the issue. Take a look a the code:
HTML:
<select>
<option>567</option>
<option>789</option>
</select>
<input id="Add" value="Add" type="button"> <input id="remove" value="Remove" type="button">
<div id="container">
<span class="item">123</span>
<br/>
<span class="item">456</span>
<br/>
</div>
JavaScript
$(".item").click(function () {
if ($("#container span").hasClass("selected")) {
$(".selected").removeClass("selected");
}
$(this).addClass("selected");
});
$("add").click(function() {
//Finds Selected option from the Select
var newSpan = document.createElement("SPAN");
newSpan.innerHTML = choice;//Value from Option
newSpan.className = "item";
var divList = $("#container");
divList.appendChild(newSpan);//I've tried using Jquery's Add method with no success
//Deletes the selected option from the select
})
Here are some methods I've already tried:
Standard jQuery click on elements with class "item"
Including using the `live()` and `on()` methods
Setting inline `onclick` event after element creation
jQuery change event on the `#Container` that uses Bind method to bind click event handler
Caveat: I can not create another select list because we are using MVC and have had issues retrieving multiple values from a list box. So there are hidden elements that are generated that MVC is actually tied to.
Use $.on instead of your standard $.click in this case:
$("#container").on("click", ".item", function(){
if ( $("#container span").hasClass("selected") ) {
$(".selected").removeClass("selected");
}
$(this).addClass("selected");
});
It looks to me like you want to move the .selected class around between .item elements. If this is the case, I would suggest doing this instead:
$("#container").on("click", ".item", function(){
$(this)
.addClass("selected")
.siblings()
.removeClass("selected");
});
Also note your $("add") should be $("#add") if you wish to bind to the element with the "add" ID. This section could also be re-written:
$("#add").click(function() {
$("<span>", { html: $("select").val() })
.addClass("item")
.appendTo("#container");
});
Say I want to modify a text by clicking on it, which turns to a input text field along with two buttons, save and cancel like below (the click event has been omitted and I am using the replaceWIth() from jQuery).
Before transformation:
<span>text<input type="button" value="delete"</span>
After transformation:
<input type="text"><input type="button" value="save"><input type="button" value="cancel">
what I want to do is if the I click on the cancel button, nothing happens and the "after transformation" part can be restore to the original part like how it looked before
<span>text<input type="button" value="delete"</span>
any way to do that? I thought I should somehow "save" before transforming like "snap" a picture or something. Any idea?
Waited till the India vs WI match was done before posting :)
This is what you want : http://jsfiddle.net/G8Kaj/4/
It uses live so that it'll work multiple times. It also works if there are multiple rows of because it simple picks up the parent and doesn't rely on there being only 1 row.
<span class='text'>text<input type="button" class='deleteButton' value="delete"></span>
$('span.text').live('click', function(){
var $this = $(this);
$this.data('oldText', $this.html());
var newText = '<input class="theText" type="text"><input class="saveButton" type="button" value="save"><input class="cancelButton" type ="button" value="cancel">';
$this.html(newText);
});
$('.cancelButton').live('click', function(e){
var $this = $(this);
var parent = $this.parent('span');
parent.html(parent.data('oldText'));
e.stopPropogation();
});
$('.saveButton').live('click', function(){
//do something on save
e.stopPropogation();
});
$('.theText, .deleteButton, cancelButton').live('click', function(){
e.stopPropogation();
});
Uses the jqery data object to store the old state on a per span basis.
Try this:
<span id="before">text<input type="button" value="delete" id="delete"/></span>
<span id="after">
<input type="text">
<input type="button" value="save" id="save"/>
<input type="button" value="cancel" id="cancel"/>
</span>
<script>
$('document').ready(function() {
// Initially hide
$('#after').css('display','none');
$('#delete').click(function() { showAfter(); });
$('#save').click(function() { hideAfter(); });
$('#cancel').click(function() { hideAfter(); });
function showAfter() {
$('#after').css('display','block');
$('#before').css('display','none');
}
function hideAfter() {
doSomething();
$('#after').css('display','none');
$('#before').css('display','block');
}
function doSomething() {
alert('I just did something!');
}
});
</script>
You are trying to implement inline-editing. This is a task better done with a JavaScript library. Most JavaScript library has modules (or plugins) that can do inline-editing -- text to textboxes, numbers to spinner boxes etc. I would not recommend recreating something that teams of library programmers have already spent hours debugging on all conceivable browser platforms.
For example, the Dojo Toolkit has dijit.inlineEditBox that needs very little coding and does most of what you want. It uses a hidden textbox to hold the previous value.
jQuery has the Edit-in-Place plugin.