Knowing the last clicked textbox via Javascript - javascript

I have a form and a button.
I need that when I click on a textfield, and then click this particular button, the textbox which was clicked last will change its value to say "BUTTON HAS BEEN CLICKED".
Is there a way via JavaScript how I can know the last textbox which was clicked?
Many thanks in advance.

You need to store a reference to the text box when you click it. The easiest way to do that is to create a global variable for the reference. Then you would update the reference with the textbox's onclick event. Here is an example:
HTML:
<input id="myTextBox" type="text" onclick="updateCurText(this);">
<input type="button" value="click me" onclick="updateText();">
JavaScript:
var currentTextBox = '';
function updateCurText(ele) {
currentTextBox = ele.id;
}
function updateText() {
document.getElementById(currentTextBox).value = 'BUTTON HAS BEEN CLICKED';
}
Live example.

jsumners is correct, however I would probably recommend avoiding global variables, and if you're using something like jQuery you have encapsulate a lot of the logic in a single file:
$(function() {
var lastBox = false, formSelector = "form.myClass";
// Change events
$(formSelector + " input[type='text']").click(function() {
lastBox = this;
});
// Button click
$(formSelector + " button").click(function() {
if (lastBox)
$(lastBox).val("BUTTON HAS BEEN CLICKED");
});
});
live

Related

How to get textarea value into a varaible outside function

How to make the variable "apry" be equal to the written data in "textarea",
So then i will can get its value into URL?
HTML:
<textarea id="post" type="text"></textarea>
<a onclick="location.href = 'http://localhost/arany/?i=' + apry + '';">Reload</a>
JS:
$(document).ready(function() {
$('#post').keyup(function() {
var apry = document.getElementById('post').value;
});
})
You are actually setting the value of apry, but the problem is you then aren't doing anything with it, including not updating your DOM element. You would need the following instead :
$(document).on("keyup", "#post", function() {
$("#theLink").attr("href", "http://localhost/arany/?i=" + $("#post").val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="post" type="text"></textarea>
<a id="theLink" href="#">Reload</a>
Theres no need for a global variable in this case. You can just listen for the click event on the reload button:
<textarea
id="post" type="text"></textarea>
<button id="reload">
Reload
$(document).ready( function() {
$('#reload').click(function() {
location.href = 'http://localhost/arany/?i=' +
$('#post').val();
});
});
http://jsfiddle.net/4j0fohr5/1/
To do what you require it would make more sense to invert the logic. Instead of creating and updating a variable which has the value of the textarea as it's typed in to, simply have an event handler which reads the value from the textarea when the a is clicked. This has the benefit of avoiding an unnecessary global variable. Try this:
<textarea id="post" type="text"></textarea>
Reload
$(document).ready(function() {
$('#reload').click(function() {
location.assign('/arany/?i=' + $('#post').val());
});
});
One thing to note here is that you will have to be careful with line breaks in the value.
Alternatively if you did want to update the href of the a as the textarea is typed in to you could use prop() to do that inside an input event handler:
<textarea id="post" type="text"></textarea>
Reload
$(document).ready(function() {
$('#post').on('input', function() {
$('#reload').prop('href', '/arany/?i=' + $(this).val());
});
});
I see that you want to add the textarea content as a query string "i" parameter when you click the "Reload" button.
For that purpose you only need an input text field instead of a textarea, since the URL does not support line break characters.
Also, you don't need to update the "i" every time you change the text, realize that you need that value just when you click the "Reaload" button.
So, here is what I propose to you to solve your problem:
<input type="text" id="post"></textarea>
<a onclick="goToLocation();">Reload</a>
function goToLocation(){
apry = window.document.getElementById('post').text();
window.location.href = 'http://localhost/arany/?i=' + apry;
}
var apry = null;
$(document).ready(function() {
$('#post').keyup(function() {
apry = document.getElementById('post').value;
});
})
This should work for you

Why doesn't javascript function update DOM on first run

I have a dynamic form in which users can add inputs by clicking a button. This works fine. However when clicking to remove the input the first click does not remove an input. Every click after removes inputs as expected. I can see that it runs the function on first click to remove but nothing is updated in the DOM so the field stays. Here is my HTML:
<button onclick="AddFileField()">Add File</button>
<br />
<br />
<form action="" method="post" enctype="multipart/form-data">
<div id="fileFields"></div>
<br />
<input type="submit" value="Upload" />
</form>
And the associated javascript:
function removeField() {
$('.removeclass').click(function () {
$(this).parent().remove();
});
return false;
}
var FieldCount = 1; //to keep track of text box added
function AddFileField() {
var MaxInputs = 10; //maximum input boxes allowed
var InputsWrapper = $("#fileFields"); //Input boxes wrapper ID
var x = $("#fileFields > div").length + 1; //current text box count
if (x <= MaxInputs) //max input box allowed
{
$(InputsWrapper).append('<div class="fileInp"><label for="file' + FieldCount + '">File:</label><input type="file" name="files" class="inpinl" id="file' + FieldCount + '" />×</div>');
FieldCount++;
}
return false;
}
A fiddle showing issue. To duplicate add a couple fields then click an x. The first click does nothing, then proceeding clicks removes fields. How can I get the first click to remove the field as well?
It's because you are registering your event handler inside of another event handler.
http://jsfiddle.net/3e1ajtvo/11/
I removed your event handler and now, you pass the clicked element as elem into the function itself.
As a matter of fact you don't even really need the function, as long as jquery is exposed (it is in your case).
http://jsfiddle.net/3e1ajtvo/12/
A working fiddle is here
The issue lies in the function:
function removeField() {
$('.removeclass').click(function () {
$(this).parent().remove();
});
return false;
}
When you click the X, this function is called, which adds a click event handler to the X to remove it; however, this event handler is not called until the next time you click it. (This is why clicking X twice works).
In the updated fiddle, you simply pass this to removeField as such:
//HTML
×</div>
//JS
function removeField(me) {
$(me).parent().remove();
return false;
}
The reason for this is because you are using onclick="removeField()".
Lets take a look at your function. When you click on the remove button the following script will run. This script then creates a click handler, that will activate on next click, because when you first clicked on remove the handler was not created
function removeField() {
$('.removeclass').click(function () {
$(this).parent().remove();
});
return false;
}
So you will need to replace this is another function. Since you are using jQuery you can learn to use .on() for dynamically generated elements.
$(document).on('click', '.removeclass', function () {
$(this).parent().remove();
});
http://jsfiddle.net/Spokey/3e1ajtvo/16/
I made your code a bit more modular and changed it to use jQuery more than you were. This is just another way to do it, the other answers are also valid.
http://jsfiddle.net/3e1ajtvo/19/
var fields = {
btnAdd: $('#addField'),
inputWrapper: $('#fileFields'),
maxInputs: 10,
fieldCount: 1,
init: function(){
this.inputWrapper.on('click', '.removeclass', this.removeInput);
this.btnAdd.on('click', this.appendField);
},
removeInput: function(){
//this will refer to the html element you clicked on
$(this).parent().remove();
},
appendField: function(){
//this will refer to the html element you clicked on
if ( fields.inputWrapper.children('div').length <= fields.maxInputs ){
fields.inputWrapper.append('<div class="fileInp"><label for="file' + fields.fieldCount + '">File:</label><input type="file" name="files" class="inpinl" id="file' + fields.fieldCount + '" />×</div>');
fields.fieldCount++;
}
}
};
fields.init();
You're not executing the code to remove the row on the first click, you're just adding the click handler to the link. It works after that because the $('.removeclass').click(... then fires as expected.

JQuery focus to previous clicked input bug

I have two input fields. The main idea is that whenever you focus to one of the fields, the button click should print a random number inside it.
My problem is that when you just focus on (click on) the first field, then focus on second (or vice versa), the button click prints to both instead of just to the (last) focused field.
You can try to recreate the problem here: http://jsfiddle.net/sQd8t/3/
JS:
$('.family').focus(function(){
var iD = $(this).attr('id');
$("#sets").one('click',function() {
var ra = Math.floor((Math.random()*10)+1);
$('#'+iD).val(ra);
});
});
HTML:
<center class='mid'>
<input type="text" class="family" id="father" />
<br/><br>
<input type="text" class="family" id="mother" />
<br/>
<br/>
<input type='submit' value='Set text' id="sets"/>
</center>
In the "focus" handler, unbind any existing "click" handler:
$('#sets').unbind('click').one('click', function() { ... });
The way you had it, an additional one-shot "click" handler is bound each time a field gets focus, because jQuery lets you bind as many handlers as you like to an event. In other words, calling .one() does not unbind other handlers. When the click actually happens, all handlers are run.
edit — sorry - "unbind" is the old API; now .off() is preferred.
Put the variable iD outside, and separate the functions:
http://jsfiddle.net/sQd8t/8/
This prevents from adding too many events on each input click/focus.
No need to unbind.
var iD;
$('.family').focus(function() {
iD = $(this).attr('id');
});
$("#sets").on('click', function() {
var ra = Math.floor((Math.random() * 10) + 1);
if (iD!="")$('#' + iD).val(ra);
iD = "";
});
See http://jsfiddle.net/sQd8t/11/
$('.family').focus(function(){
$("#sets").attr('data-target',$(this).attr('id'))
});
$("#sets").click(function() {
var target=$(this).attr('data-target');
if(target){
var ra = Math.floor((Math.random()*10)+1);
$('#'+target).val(ra);
}
});
You can create a data-target attribute which contains the field which must be modified.

use button to write text to the page

I can do this with a alert but I want to print the results of a function directly to the web page.
When the user clicks the car button I want the results from the car() function to write into my id="mainContent" div.
if the user clicks the Ice Cream button I want the results from the ice cream button to replace what ever is in the mainContent div with the results from the iceCream() function
var mainContent = document.getElementById('mainContent');
carButton.onclick = function() {
mainContent.appendChild(document.createTextNode(car()));
}
Assuming you have some code like this:
<form id="ice_cream_form" action="fake" method="post">
<input type="submit" value="Ice Cream" />
</form>
You could use some JavaScript code like this:
var form=document.getElementById("ice_cream_form");
var mainContent=document.getElementById("mainContent");
if(form.addEventListener) {
form.addEventListener("submit", submitted, false);
}else if(form.attachEvent) {
form.attachEvent("onsubmit", function() {
return submitted(window.event);
});
}
function submitted(event) {
if("textContent" in mainContent) {
mainContent.textContent=iceCream();
}else{
mainContent.innerText=iceCream();
}
event.preventDefault();
event.stopPropagation();
return false;
}
If iceCream returns HTML you want to display rather than plain text you want to display, you'll probably want to replace the part that changes textContent to just set innerHTML.
Alternatively, you could use inline event handlers (although I don't really like this method because it mixes content and behavior):
<input type="button" value="Ice Cream" onclick="document.getElementById('mainContent').textContent=iceCream(); return false;" />
When, for example, the car button is clicked, this code should be run:
document.getElementById("mainContent").appendChild(
document.createTextNode(car())); /* ← there is the magic */
If you don’t know how to register this function to be launched in case of clicking the button.
Then do it like this:
var button = document.getElementById("idOfTheButton");
button.addEventListener("click",
function()
{
document.getElementById("mainContent").appendChild(
document.createTextNode(car()));
}, 1);
Adapt this code appropriately for the other button and it will work too.

How to hide a dom element after creating it on the fly with JQuery?

I am trying to build a form where users can add a text field by clicking on a "add option" button. They can also remove added fields by a "remove option" link created on the fly by Jquery, along with the text field.
JavaScript:
$(document).ready(function(){
$("#add_option").click(function()
{
var form = $("form");
var input_field = '<input type="text" />';
var delete_link = 'remove';
form.append(input_field + delete_link);
return false;
});
$("a").click(function()
{
alert('clicked');
return false;
});
});
When I click on the "add_option" button, a new text field and the "delete_link" appear. But when clicking on the "delete_link" created by JQuery, the browser follows the link instead of launching a pop-up displaying "clicked".
How do I hide a dom element after creating it on the fly with JQuery?
I'd use delegate because its uses less bubbling :
$(document).delegate("a", "click", function(){
alert('clicked');
});
EDIT , here is your code you need to change :
$(document).ready(function(){
$("#add_option").click(function(){
var form = $("form");
var input_field = '<input type="text" />';
input_field.addClass = "dynamic-texfield";
var delete_link = 'remove';
form.append(input_field + delete_link);
return false;
});
Then comes the delegate part :
$(document).delegate(".delete-trigger", "click", function(){
alert('ready to delete textfield with class' + $(".dynamic-texfield").attr("class"));
});
Try binding the handler for the <a> with "live"
$('a').live('click', function() { alert("clicked); });
You probably should qualify those <a> links with a class or something.
I don't get why you're using a <a> as a button to execute a function in jQuery. You have all the tools you need right in the framework to totally bypass well-worn traditions of HTML.
Just put a css cursor:pointer definition on the button you want to appear "clickable," add some text-decoration if that's your fancy, and then define your function with jQ:
$('.remove-button').live('click', function() {
$(this).parent().remove();
}

Categories