JQuery trigger a button click once - javascript

I am trying to build a jQuery function that creates seven input fields when a button is clicked. This should be allowed only once, and not every time the button is pressed.
At the moment I have the below code that creates one text field, but the problem is that every time the button is pressed more text fields are added. By creating these text fields I can use them to add records in my database. For example by clicking the addbutton, the text fields will be created and the user could enter the information.
$("#addbutton").bind("click", function() {
var textarea = $('<input type="text" name="firstname">',);
$('#textfields').append(textarea);
});
Thanks

You can fire the event handler only once with one(), and just append the buttons you want, I'm using an array of names and $.map to create them
$("#addbutton").one("click", function() {
var buttons = [
'firstname',
'lastname',
..... etc
];
$('#textfields').append(
$.map(buttons, function(_name) {
return $('<input />', { name : _name })
})
);
});
FIDDLE

According to our chat in your comments, you want a button that:
On click, it creates seven input fields and appends them to your #textfields element.
After the fields are created, the button is not allowed to create any more input fields.
I devised the following solution based upon this interpretation:
$("#addbutton").click(function(){
for(var i = 0; i < 7; ++i){
$('#textfields').append('<input type="text" name="firstname">');
}
$(this).prop("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="addbutton">Click Me</button>
<div id="textfields"></div>
Long story short, the button is disabled after the first click. This prevents you or anyone from doing anything else with the button.
Alternatively you could create a global variable which will act as a flag, to help prevent further input fields from being created, by wrapping the input creation code with an if statement like so:
var inputFieldsCreated = false;
$("#addbutton").click(function(){
if(inputFieldsCreated === false){
for(var i = 0; i < 7; ++i){
$('#textfields').append('<input type="text" name="firstname">');
}
inputFieldsCreated = true;
}
});
Let me know if this does the job for you in the comments below.

Just because I don't like using JQuery for such easy/simple/short thing, here's the code with pure JavaScript :
document.getElementById("btn").addEventListener("click", onClick, false);
function onClick() {
var textfield, br;
for(var i=0 ; i<7 ; i++) {
textfield = document.createElement("input");
br = document.createElement("br");
textfield.id = "txt_"+i;
document.getElementById("textFields").appendChild(textfield);
document.getElementById("textFields").appendChild(br);
}
this.parentElement.removeChild(this);
}
cou can test it here :
https://jsfiddle.net/v91v7afa/
Of course, instead of deleting the button, you can disable it, but it would be really easy to re-enable it. Or you can remove the listener.

var numText=1;
$("#addbutton").on("click",function(e){
e.preventDefault();
numText++;
$('#textfields').append('<input type="text" name="firstname" />');
if (numText==7)
$(this).off('click')
});

Related

How to validate a memorized value in an input box

I have the following code:
$(":input").bind("keyup change", function(e) {
var comboVal = $('.emailrequerido1').val()+$('.emailrequerido2').val()+$('.emailrequerido3').val()+$('.emailrequerido4').val()+$('.emailrequerido5').val();
if(comboVal == 'nullnull' || comboVal == ""){
$("#enviarForm").attr('disabled', true);
}else{
$("#enviarForm").removeAttr('disabled');
}
});
What I am trying to accomplish is that when you select a memorized value from the input box by double clicking in the box a history of inputs shows (these values are saved by the browser (I believe)) and if you choose one of these and the field has that text you selected the button should enable.
Here is a JSFiddle example: JSFiddle example
In the example I added a value to the first field since these dont memorize as I expalined before to show a demonstration of what I mean.
I have cleaned up the code a bit: http://jsfiddle.net/kam5B/1/
I've swapped the classes and ids so that the ids are unique, and the classes are common.
Here is a checkEmails function that runs the validation and enables/disables the checkbox.
checkEmails is run every time an input changes, and when the page loads the first time:
$(document).ready(function () {
function checkEmails() {
var nonempty = $('form .email_contactopadrino').filter(function() {
return $(this).val() != '';
});
if (nonempty.length) {
$('#enviarForm').removeAttr('disabled');
}
else {
$('#enviarForm').attr('disabled', true);
}
};
$('form').on('keyup change', '.email_contactopadrino', checkEmails);
checkEmails();
});

Javascript: select the text in the currently focussed input field

I would like to select the text of the input field which currently has focus, so when the user starts typing, the text which is currently in the input field is gone. Can I do this with javascript (or jquery)?
In case the field which currently has focus is not an input field, nothing has to happen.
thanks!
EDIT:
To all the answerers: you all misunderstood (so probably my question was not clear).
I don't want to select the text on the moment the input field gets the focus. I would like to have a javascript function which selects the text of the input field which has the focus at that moment.
Sorry I misunderstood what you were looking for I think that I have a better understanding of it now. Does this do more of what you were looking to acheive?
//If not using 1.7 for jquery you can use bind
$('input, textarea').on({
focusin: function(){
$(this).addClass("focused");
},
focusout: function(){
$(this).removeClass("focused");
}
});
function highlightText()
{
var focused = $('input.focused,textarea.focused');
if (focused.size()) {
focused.get(0).select();
}
}
http://jsfiddle.net/GXFpR/1/
This should work:
<html>
<head>
</head>
<body>
<input type="text" id="theTextBox" onfocus="selectText()" value="some value"></input>
<script type="text/javascript">
function selectText() {
document.getElementById("theTextBox").select();
};
</script>
</body>
</html>
You can check with onfocus and then use this.select() as inline
<input name="" type="text" value="test test" onfocus="this.select()" />
UPDATE: a more universal approach, will add focus to inputs of the text type also input text's that are not readonly
window.onload = setFocus();
or call beneth the last form input field
setFocus();
main
setFocus = function(){
var i = [];
i = document.getElementsByTagName("input");
for(var t=0; t < i.length; t++){
if(i.item(t).type == "text" && i.item(t).readOnly == false){
i.item(t).onfocus = function (){this.select()};
}
}
}
You can try something like this? http://jsfiddle.net/z55UZ/
$("input, textarea").focus(
function()
{
this.select();
}
)
EDIT:
here is an updated fiddle: http://jsfiddle.net/IrvinDominin/z55UZ/2/
In the example is selected the last focused element; but if you look at the code the var childInputHasFocus and whoHasFocus are never setted to false...when you want to stop the selecting feature?
Where you wanna call the function? Because the click event sets the active/focused element as is caller.

Change image if any checkbox on the page was checked or unchecked?

I have a lot of checkboxes with different IDs on the page.
I want to change picture everytime when any checkbox was checked or unchecked...
Please, tell me how to do that..
The basic code is shown below. Bind a onchange event to each input[type=checkbox].
$(':checkbox').change(function(){
$('#imgid').attr('src', 'newimg.png');
})
Pure JavaScript:
var inputs = document.getElementsByTagName("input");
for(var i=inputs.length-1; i>=0; i--){ //Loop through each input element in the page
var input = inputs[i];
if(input.type == "checkbox"){
input.onchange = function(){ //Bind `change` event handler
document.getElementById("imgId").src = "newimg.png";
}
}
}
Note: The previously shown code snippets have to be called when the document has loaded. Either by using window.onload = function(){ /*Code here*/ }, or by adding the code at the end of the document.

Change onclick action with a Javascript function

I have a button:
<button id="a" onclick="Foo()">Button A</button>
When I click this button the first time, I want it to execute Foo (which it does correctly):
function Foo() {
document.getElementById("a").onclick = Bar();
}
What I want to happen when I click the button the first time is to change the onclick function from Foo() to Bar(). Thus far, I've only been able to achieve an infinite loop or no change at all. Bar() would look something like this:
function Bar() {
document.getElementById("a").onclick = Foo();
}
Thus, clicking this button is just alternating which function gets called. How can I get this to work? Alternatively, what's a better way to show/hide the full text of a post? It originally starts shorted, and I provide a button to "see the full text." But when I click that button I want users to be able to click the button again to have the long version of the text go away.
Here's the full code, if it helps:
function ShowError(id) {
document.getElementById(id).className = document.getElementById(id).className.replace(/\bheight_limited\b/, '');
document.getElementById(id+"Text").className = document.getElementById(id+"Text").className.replace(/\bheight_limited\b/, '');
document.getElementById(id+"Button").innerHTML = "HIDE FULL ERROR";
document.getElementById(id+"Button").onclick = HideError(id);
}
function HideError(id) {
document.getElementById(id).className += " height_limited";
document.getElementById(id+"Text").className += " height_limited";
document.getElementById(id+"Button").innerHTML = "SHOW FULL ERROR";
document.getElementById(id+"Button").onclick = "ShowError(id)";
}
Your code is calling the function and assigning the return value to onClick, also it should be 'onclick'. This is how it should look.
document.getElementById("a").onclick = Bar;
Looking at your other code you probably want to do something like this:
document.getElementById(id+"Button").onclick = function() { HideError(id); }
var Foo = function(){
document.getElementById( "a" ).setAttribute( "onClick", "javascript: Boo();" );
}
var Boo = function(){
alert("test");
}
Do not invoke the method when assigning the new onclick handler.
Simply remove the parenthesis:
document.getElementById("a").onclick = Foo;
UPDATE (due to new information):
document.getElementById("a").onclick = function () { Foo(param); };
Thanks to João Paulo Oliveira, this was my solution which includes a variable (which was my goal).
document.getElementById( "myID" ).setAttribute( "onClick", "myFunction("+VALUE+");" );
I recommend this approach:
Instead of having two click handlers, have only one function with a if-else statement. Let the state of the BUTTON element determine which branch of the if-else statement gets executed:
HTML:
<button id="a" onclick="toggleError(this)">Button A</button>
JavaScript:
function toggleError(button) {
if ( button.className === 'visible' ) {
// HIDE ERROR
button.className = '';
} else {
// SHOW ERROR
button.className = 'visible';
}
}
Live demo: http://jsfiddle.net/simevidas/hPQP9/
You could try changing the button attribute like this:
element.setAttribute( "onClick", "javascript: Boo();" );
What might be easier, is to have two buttons and show/hide them in your functions. (ie. display:none|block;) Each button could then have it's own onclick with whatever code you need.
So, at first button1 would be display:block and button2 would be display:none. Then when you click button1 it would switch button2 to be display:block and button1 to be display:none.
For anyone, like me, trying to set a query string on the action and wondering why it's not working-
You cannot set a query string for a GET form submission, but I have found you can for a POST.
For a GET submission you must set the values in hidden inputs e.g.
an action of: "/handleformsubmission?foo=bar"
would have be added as the hidden field like: <input type="hidden" name="foo" value="bar" />
This can be done add dynamically in JavaScript as (where clickedButton is the submitted button that was clicked:
var form = clickedButton.form;
var hidden = document.createElement("input");
hidden.setAttribute("type", "hidden");
hidden.setAttribute("name", "foo");
hidden.setAttribute("value", "bar");
form.appendChild(hidden);
See this question for more info
submitting a GET form with query string params and hidden params disappear

By JQuery, how to specify on function as onClick handler for many radio buttons?

I have a function called handleOnClickRadio(i, j); and lots of radio buttons named as id="something-radio[i][j]". All these radio buttons are in a table called "bigtable".
How could I attach the function handleOnClickRadio() to all these radio buttons? And call it correct with handleOnClickRadio(i,j).
Thanks.
I would not attach the click handler to the buttons at all. You say you have lots of them. Attaching the same event handler to each of them is a waste of memory and could even be a performance problem.
Use event delegation instead:
$('#tableID').delegate('input[type=radio]', 'click', function() {
// code here
});
Then you could extract the i and j via regular expression (you could also consider to change the pattern so that you can use something simpler like split()):
var exp = new RegExp("\\[(.+?)\\]\\[(.+?)\\]", 'g');
var match = exp.exec(this.id);
var i = match[1];
var j = match[2];
You could put this together like so:
$('#tableID').delegate('input[type=radio]', 'click', function() {
var match = this.id.match(/\[(.+?)\]\[(.+?)\]/)
var i = match[1]; // use parseInt(match[1]) if you need an integer
var j = match[2];
handleOnClickRadio(i,j);
});
edit: Made code a bit simpler.
If i and j correspond to column and row indicies, see #Caspar Kleijne's answer for an alternative way to retrieve them.
For accessibility, you should consider binding the handler to the change event. Then changes via the keyboard will be recognized too.
wire up the event like this
$("#bigtable input[type='radio']").bind("click", OnClickRadio);
and use the handler like
var OnClickRadio = function () {
var col = $(this).parent("td").index();
var row = $(this).parent("td").parent("tr").index();
handleOnClickRadio(col, row)
});
You can attach an onClick method to a collection of radio buttons within a table with a simple bit of jQuery. When you say 'table called "bigtable"', I'm assuming that you mean that it has id="bigtable" in the following code.
$(document).ready(function() {
$("#bigtable input:radio").click(function() {
// Your on click code here
});
});
However, I would usually give each of the radio buttons a specific class using class="magicRadioButton" and then your jQuery code becomes a little clearer and doesn't rely on all of those radio buttons being within a table;
$(document).ready(function() {
$(".magicRadioButton").click(function() {
// Your on click code here
});
});
Now, if you need to then plug this information into your current handleOnClickRadio method, you can do so with the following.
$(document).ready(function() {
$("#bigtable input:radio").click(function() {
var button_id = $(this).attr("id");
var re = new RegExp("\\[(.*?)\\]\\[(.*)\\]");
var matches = re.exec(button_id);
var i = matches[1];
var j = matches[2];
handleOnClickRadio(i,j);
});
});
Give them class names in conjunction with $(this) in your click trigger
I suggest using delegate if you have lot of radios: that way, only one Event listener will be attached
see http://api.jquery.com/delegate/
$("#globalContainer").delegate("input", "click", function(){
//Perform a string test / regex to test if the id matches something-radio[i][j]
//With a regex with capturing groups you can retrieve [i] and [j] values at the same time
if ( test($(this).attr("id")) ) {
}
});
Ideally, you'd have a onclick assigned to the big table rather than each and every radio button. Events in JavaScript bubble up so the table (which is the eventual parent of all these radio buttons) will receiving the event.
So in jQuery you would have code like this
$('#bigtable').click(handleOnClickRadio);
The signature of your handleOnClickRadio function would be
function handleOnClickRadio(evt) {
var radio = evt.target;
var id = $(radio).attr('id');
}
evt.target will identify the actual radio button that was clicked/checked and you can access other attributes of the radio as well. such as
$(radio).attr('id)
Will give you the id of the radio button.
<input type="radio" class="many-radio-buttons" ....
jQuery:
$('.many-radio-buttons').click(function() {
//your_code;
});

Categories

Resources