I have <form>s on my page that I want to replace with <button>s. The thing that is causing me difficulty is that I want to use the value of the <form>'s submit input as the html for the button.
<form action="/postcomment/" method="post">
<inputs>
.
.
.
<input type="submit" value="Reply">
</form>
Becomes
<button class="postcomment">Reply</button>
I'm having a hard time wrapping my mind around the chaining here. I need to grab the data values (e.g. "Reply") and then insert them into the button elements in one jQuery operation (or else manage the ordering with something like .index()) and I haven't figure out how to do that yet.
Working example here: http://jsfiddle.net/Mch86/
$(document).ready(function(){
$('form').each(function(){
button = $('<button>' + $('input[type="submit"]', this).val() + '</button>').addClass($(this).attr('action').replace(/\//g, ''));
$(this).replaceWith(button);
});
});
Do something like this:
$('input[type="submit"]').replaceWith(function () {
return $('<button>').text(this.value).addClass('postcomment');
});
jsFiddle Demo
This will replace all of your submit buttons (<input type="submit">) with a <button>, keeping the text on the button.
replaceWith() allows you to use a function as its parameter, which has a reference to the individual submits themselves (this).
Since you said you have multiple forms:
$(function() {
$('form').each(function() {
var str = $(this).find('input[type="submit"]').val();
$(this).replaceWith($('<button/>').addClass("postcomment").text(str));
});
});
You could do:
var label = $('form input:submit').val();
var action = $('form').attr('action').replace(/\//g, '');
var button = $('<button />', { class: action});
button.html(label);
$('form').replaceWith(button)
;
fiddle here: http://jsfiddle.net/be3af/1/
Related
I need to have multiple buttons on page (created through a PHP loop) - there's not fixed number of buttons as there'll be one for each record displayed. I'd like to get the value of that button with javascript when it is clicked.
So far the html looks like:
<button id="update[0]" value="test">Update</button>
<button id="update[1]" value="test">Update</button>
<button id="update[2]" value="test">Update</button>
etc....
and my script is:
$(document).ready("#update").click(function() {
var updateId = $("#update").val
alert(updateId);
});
So far the script detects when any #update[] button is clicked but how do I know the index of the particular button in order to get the value (i.e. if #update[38] is clicked how do I know it's #update[38] so I can find the value of that particular button?
Thanks.
You do not want to chain off the document ready like you are as its returning the document.
$(document).ready("#update").click(function() {
So you are capturing the document.click not not button.click so when you reference $(this).val() you will get document.value which does not exist.
Should be:
$(document).ready(function () {
$("button").click(function () {
//no reason to create a jQuery object just use this.value
var updateId = this.value;
alert(updateId);
});
});
http://jsfiddle.net/SeanWessell/2Lf6c3fx/
Use the "this" key word.
$(document).ready("#update").click(function() {
var updateId = $(this).val();
alert(updateId);
});
The this keyword in javascript allows you to reference the particular instance of the object you are interacting with.
Also, add "()" to the end of val.
I believe you meant to use
var updateId = $("#update").val()
With jQuery you can use $(this).val()
You could also get the text of the button using .text()
With pure Javascript you could use .value if the button has a value attribute
See this: Javascript Get Element Value
I would suggest the following
<button id="0" class="updatebutton" value="test">Update</button>
<button id="1" class="updatebutton" value="test">Update</button>
<button id="2" class="updatebutton" value="test">Update</button>
Use a class to apply your click function.
$(document).ready(function () {
$("updatebutton").click(function () {
var updateId = this.id;
alert(updateId);
});
});
And use the id to specify the index of the button.
The trick is to give all your buttons the same class and then use $(this) to find out which button was clicked.
Once you know the button, then you can check for any of its attributes like id, value or name.
$(function() {
$(".xx").on("click", function(evt) {
var clicked_button = $(this);
alert(clicked_button.attr("value"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="update_1" class="xx" value="test1">Button 1</button>
<button id="update_2" class="xx" value="test2">Button 2</button>
<button id="update_3" class="xx" value="test3">Button 3</button>
Hi there a few things wrong with your javascript there.
You are attaching onClick to the document! The function ready returns the document.
Wrong:
$(document).ready("#update").click(function() {
Right:
$(document).ready(function () { $(valid_selector).click...
You are attempting to refetch the button with $('#update'), which 1 doesn't fetch anything, and two if it did would return all of the buttons. So use $(this) in the scope of the click function instead to refer to the button clicked.
Here is your javascript corrected:
https://jsfiddle.net/ffkekpmh/
//When the document is ready call this function
$(document).ready(function () {
//Select all buttons whoes id starts with update
//https://api.jquery.com/category/selectors/attribute-selectors/
$('button[id^="update"]').click(function() {
//Store the id attribute from the clicked button
var updateId = $(this).attr("id");
//Store the value attribute from the clicked button
var value = $(this).attr("value");
alert("You clicked button:"+updateId+" with value: "+value);
});
});
I need to use two plug-ins in one element on my page. I've never needed to do this and tried as it is in the code below. Most did not work!
<script type="text/javascript">
$(document).ready(function()
{
var wbbOpt = {buttons: "bold,italic,underline,|,img,link,|,code,quote"}
// plugin one wysibb
$("#editor").wysibb(wbbOpt);
// plugin two hashtags
$("#editor").hashtags();
//the two plugin worked in textarea #editor
});
</script>
Can anyone help me? Thank you.
So you can't use them because each of them take control and wrap the textarea. Since the editor is the most complex of the two the best thing to do is to take the code of the hashtag and adapt it at your need.
So here's a working example, but if you want you can trigger the function I use to the change event (adding it) or some way else
<div id="higlighter" style="width;1217px;"></div>
<textarea id="editor"></textarea>
<br />
<input id="btn" type="button" value="HASH">
<br />
$(document).ready(function() {
var wbbOpt = {
buttons: "bold,italic,underline,|,img,link,|,code,quote"
};
$("#editor").wysibb(wbbOpt);
$('#btn').click(function () { report() });
});
function report() {
$("#hashtag").val($("#editor").htmlcode());
var str = $("#editor").htmlcode();
str = str.replace(/\n/g, '<br>');
if(!str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([a-zA-Z0-9]+)/g)) {
if(!str.match(/#([a-zA-Z0-9]+)#/g)) {
str = str.replace(/#([a-zA-Z0-9]+)/g,'<span class="hashtag2">#$1</span>');
}else{
str = str.replace(/#([a-zA-Z0-9]+)#([a-zA-Z0-9]+)/g,'<span class="hashtag2">#$1</span>');
}
}
$("#editor").htmlcode(str);
}
you can check a working code here on jsfiddle.
http://jsfiddle.net/4kj7d6mh/2/
You can type your text and use the editor, and when you want to higlight the hastag you click the button. If you want that to happen automatically you have to change this line:
$('#btn').click(function () { report() });
And attach the function to the keypress for example (experiment a bit)
I've had this problem for awhile now and I can't seem to fix it no matter what I do.
Basically, my input is not retrieving the value that the user types in the input for some reason..
Here is my code:
$('#aid').one('click', function () {
$('.prompt').prepend('<tr class="task"><td class="cell-icon"></td>' +
'<td class="cell-title"><div>User\'s Object: <input id="inputObject" type="text" style="margin-top: 2px;margin-left:2px"></input> Amount: <input id="inputAmount"' +
'type="text" style="margin-top:2px;margin-left:2px; padding-right: 0px"></input></div></td>' +
'<td class="cell-status hidden-phone hidden-tablet"><a class="btn btn-success" style="margin-top:3px">Submit</a></td>' +
'<td class="cell-time align-right">Just Now</td></div>' +
'</tr>');
});
$('.btn').click(function () {
console.log("click");
var input = document.getElementById('inputObject').value;
console.log(input);
});
Everything works fine including both clicks, but for some reason it just won't display the input value to the console.
I've also tried: $('#inputObject').val(); but that didn't work either.
I really hope that someone can help me here!
Another method: use delegate.
$('body').delegate('.btn', "click", function() {
var inp = document.getElementById("inputObject").value;
console.log(inp);
});
Explanation from http://www.w3schools.com/jquery/event_delegate.asp:
The delegate() method attaches one or more event handlers for specified elements that are children of selected elements, and specifies a function to run when the events occur.
Event handlers attached using the delegate() method will work for both current and FUTURE elements (like a new element created by a script).
You are creating your HTML code dynamically so try using:
$(document).on("click",".btn", function(){
do stuff here...
});
I want to add multiple input values in an input field with jQuery. So that everytime I hit the button, a new value is added in the same field along with the old value.
I am trying following code, but it does not add the value, it simply overwrites the previous value.
HTML:
<div class="wrap">
<button>Add value</button>
<input name="myinput[]" value="" />
</div>
jQuery:
$("button").click(function(e) {
e.preventDefault();
$(this).parent().find('input[name=myinput\\[\\]]').val("value+");
});
Demo:
http://jsfiddle.net/D97bV/
You add strings together with +
$("button").on('click', function(e) {
e.preventDefault();
var elem = $(this).parent().find('input[name=myinput\\[\\]]');
elem.val( elem.val() + 'add this' );
});
FIDDLE
Now you only need something useful to add ?
Try:
$("button").click(function(e) {
e.preventDefault();
var val = $(this).parent().find('input[name=myinput\\[\\]]').val();
$(this).parent().find('input[name=myinput\\[\\]]').val(val+"value+");
});
DEMO FIDDLE
try this:
$("button").click(function(e) {
e.preventDefault();
var myInput = $(this).parent().find('input[name=myinput\\[\\]]');
myInput.val(myInput.val() + "value+");
});
I have a button :
<button id="btn1">55</button>
And so I change the button value to test2
$('#btn1').text("22");
I want to show a background-picture if the buttons oldValue greater then the newValue.
How can I get the old value from this button?
"I have over 100 buttons and they are changing dynamically."
Update: Isn't there an event that fires before it changes?
You could use jQuery's .data() call and store it for retrieval as needed.
For instance, say you HTML is:
HTML
<form action="#" method="GET">
<input type="text" value="369" />
<button id="btnID">420</button>
</form>
You could easily first gather the data needed and asign it to each element:
Opening script
$("button") // would simply grab all buttons, you can use whatever css selector
.each(function(i) {
$(this).data("prevVal", parseInt($(this).text()));
});
You can then later check this value against a new value as needed:
... some change function
$('#btn1').text("22");
if ($('#btn1').data("prevVal") > 22) {
// do work
}
$('#btn1').data("prevVal", 22)
Just FYI
If you were using inputs instead it would be easier:
$("input").each(function(i) { $(this).data("prevVal", parseInt($(this).val())) })
.on("change", function(e) {
var newVal = parseInt($(this).val());
if ($(this).data("prevVal") > newVal) {
// do work
};
$(this).data("prevVal" newVal);
});
Or if you wanted to maintain a list of values:
$("input").each(function(i) {
$(this).data("vals", new Array());
$(this).data("vals").push(parseInt($(this).val()));
})
.on("change", function(e) {
$(this).data("vals").push(parseInt($(this).val()));
var vals = $(this).data("vals");
if (vals[vals.length-1] > vals[vals.length-2]) {
// do work
};
});
You need to compare it before changing value.
For example
$('#btn1').text(function (index, old) {
if (parseInt(old) > 22) {
//change background image
}
return "22";
});
FIDDLE
Unless you preserve it before the change you cannot get the old value. The change event is fired after the value has been changed already.
Not sure where you want the old value.. but if it while changing the text then use the function to change the text.
$('#btn1').text(function (index, oldvalue) {
console.log(oldvalue);
return "test2";
});
<button id="btn1">test1</button>
$(document).ready(function(){
var i=1;
$('#btn1').click(function(){
$(this).data('old', $.trim($(this).text())).text('btn'+(++i));
alert( $(this).data('old'));
});
});
for demo
use jQuery.data() to store data associated with the specified element and you will be able to get it just by accessing the same element.
Here's the link to show you how to use jQuery.data();
Here's the code using a more convenient .data() link
Set
$("#btn1").data("oldVal", $("#btn1").html());
Get
$("#btn1").data("oldVal");
Fiddle