Passing TextBox Value to a unique label? - javascript

I am just getting into Jquery and I am stuck on a little bit of a bug. In my HTML I generate some H tags and Labels. These H tags and Labels have an on click function that will take that element whether it be an H tag or Label and pass it off to a method (setProperties(this)).
This method will capture what was written inside the input field and assign it to that element. My bug is that after I click on 2 elements it will change to whatever was in the input on both. I am assuming the elements are now listening to the input field and assigning there text value to what was inside the input field. I am curious on how I could rearrange my code to make what ever you element you click on. That field will be the unique field to change.
Variables :
Element is the element I click on such as a H tag or Label
the id ChangeText is the input element where you type to change the label or H tags value.
function inputfield(element){
$("#changeText").on("blur",function(){
$(element).text($("#changeText").val());
});
}
Here is a Jfiddle of what my problem is. If you click on two of the test texts and then change the value of the input. It will change both. I am looking to change only one.
http://jsfiddle.net/QMsQq/5/

It appears that when the inputfield function is called, you are setting the onblur to fire.
The on function will last after the inputfield function call. Try calling "off" to remove prior set on events from changeText.
function inputfield(element){
$("#changeText").off().on("blur",function(){
$(element).text($("#changeText").val());
});
}
Warning: untested code.
http://jsfiddle.net/QMsQq/6/ Updated your fiddle to show my solution

Assign the element to a variable.
var $elem = $('whatever');
and pass that as the argument. And I think you want to fire on focus of an element (click).
Also, here is a VERY simple vanilla js example of what I think you're getting at:
http://jsfiddle.net/Lqf25/3/
Hopefully that helps a smidge.
Edit:
ok, for your fiddle:
Your input syntax is jacked. (missing '>' and you don't need '/input' anyway)
Don't use (onClick) in html. Separate your concerns - javascript goes in the script file, not inline. See my fiddle for an example. Although, from reading your latest posts I don't think it's quite what you want - I'm actually a little confused on what exactly you're trying to do...
Edit 2:
Try this: http://jsfiddle.net/w88xr/3/
I think that's what you're looking for.

Related

Output doesn't appear in Input field but value exists

I am confused, I used jQuery to $("#display").html(value) toward my html input with id ="display" but nothing appears in the html input.
However we can see the value in the element : "32" (see picture)
Any idea why the value doesn't appear?
I try to replace input by span and it works well.
image : example
thanks,
Thomas
You cannot set the innerHTML value of an input element (which is what jQuery is doing when you use $.html()). Instead, you need to use $.val().
Try using $("#display").val(value) instead.

Building an element with jQuery gets me an error

I am trying to make an element with jQuery, which contains text from an input field after the user clicks the SUBMIT button.
Here is my jsfiddle: http://jsfiddle.net/2y26rzot/
Here is my javascript:
$(document).ready(function () {
$('button[type=submit]').click(function () {
var typedText = $('input[type=text]').val();
var resultText = $('<p></p>').text(typedText+'2');
$('section.result').append(resultText);
console.log(typedText);
alert(typedText);
console.log(resultText);
alert(resultText);
});
});
I have included bootstrap js and css and of course jQuery as well.
The problem occurs somewhere between the first and the second alert, but I have no idea where and why. I have basic understanding of jQuery, as I learned it by doing, so I may be getting something wrong here.
The error on my local machine reads:
text
index.html:45 [p, jquery: "1.11.0", constructor: function, selector:
"", toArray: function, get: function…]
Navigated to file:///C:/Users//Desktop/textonbackground/index.html?
Of course if I remove the last 2 lines with the resultText console log and alert I don't get an error, but the text still vanishes and I don't understand why. Can someone explain this to me and of course suggest some other way to achieve my goal, namely to get information from the input field and post it as a paragraph on the page.
I should mention that I've tried different approaches building the variables and appending the text (with .add and .after) but nothing changed. I am missing something here.
Your help is much appreciated!
The text disappears because the page refreshes after form submission. The problem is not in .text()
If you add e.preventDefault() to it, the text will stay where it should.
If you don't want to change the event, you could use a regular button (<button type="button">) without the form
Online here: http://jsfiddle.net/2y26rzot/3/
Your code seems to work fine in the fiddle, you just need to prevent the default action of the form submitting (if it submits it will refresh the page and so your clientside changes, ie. the changes made with js, will not show):
$('button[type=submit]').click(function (e) {
e.preventDefault();
...rest of code
});
Updated Fiddle
If you want to append a p element, with a text inside, you should bascalliy do
var resultText = $('<p>'+typedText+'2</p>');
Because .text() returns either the text of the concerned element if you dont pass any argument (to get text), or the jquery object of the concerned element if you pass an argument (to set text)

Unexpected JS behavior when clearing input field value - STCombobox

I am using some JQuery Combobox that you can check out here: https://simpletutorials.com/uploads/1860/demo/index.html
As you can see, you can start typing and get the results filtered.
However, once you have selected a value, when clicking on the arrow to open the list, no other values are shown anymore. So, if I want to change college/state, I need to manually clear the input value. I don't like this, so I want to modify it.
I changed that code and added this JS on the click event of the list:
onclick="document.getElementById('statesCombo-ddi').value='';"
This line basically finds the input by id and sets its value to an empty string.
You can try out by looking for the td element having class "stc-button" (with Chrome, just focus on the arrow of the second combo box) and add my code to the tag.
===EDIT===
You can obtain the same results by adding this code directly to the input:
onclick="this.value=''"
===END EDIT===
This has a weird behavior:
If I SELECT an element from the list, it clears the value and everything works correctly.
If I TYPE some letters and then select a value from the list, no item is shown in the list after clicking.
What's wrong with it?
You can override one of the combo box methods to accomplish this:
STComboBox.prototype.filterAndResetSelected = function() {
this.$('ddi').val('');
this.filterList('');
this.selectRow(0);
this.$('ddl').scrollTop(0);
};
Does this help?
The unminified code is provided, is relatively small (12kb) and is fairly well commented, so you could make this modification directly to the source if you'd like.
Edit: Fixed to clear the input value (as indicated in the comment below)
By reading the source and doing a little debugging with Chrome's inspector (Control+Shift+i), you can find the particular ID of the element you need to clear (#collegesCombo-ddi) in order to clear the input box. Once you've found the element's ID you need to clear (and being very careful with plugins that assign multiple elements with the same ID, which is not allowed in the standard, and an indicator of poorly-written code):
$('#collegesCombo-ddi').val('');

Grab text input as the user types

I'm trying to update a span tag on the fly with data from an input text field. Basically I have a text field and I'd like to be able to grab the user's input as they type it and show it to them in a span tag below the field.
Code:
<input id="profileurl" type="text">
<p class="url">http://www.randomsite.com/<span id="url-displayname">username</span></p>
JQuery:
var username;
$('#profileurl').keyup(function(username);
$("#url-displayname").html(username);
See it in JS Fiddle: http://jsfiddle.net/pQ3j9/
I'm guessing the keyup function is not the best way to do this. Since checking the key wouldn't be able to grab prefilled or pasted form input.
Ideally there is some magical jQuery function that can just output whatever info is in the box whenever it detects a key up but if that method exists I haven't found it yet.
EDIT: You guys are fricken amazing. It looks like .val() is that magic method.
Second question: How would you restrict input? Looking at the modified jsfiddle's, when a user inputs an html tag like < hr > the browser interprets it and breaks the form. Do you specify an array and then check against that? Does jquery have anything like PHP's strip_tags function?
$('#profileurl').keyup(function(e) {
$("#url-displayname").html($(this).val());
}).keypress(function(e) {
return /[a-z0-9.-]/i.test(String.fromCharCode(e.which));
});
check out the modified jsfiddle:
http://jsfiddle.net/roberkules/pQ3j9/5/
Update: As #GregL points out, keyup indeed is better, (otherwise e.g. backspaces are not handled at all).
Similar to roberkules' answer, but using keyup() like you proposed seems to work better for me in a Chrome-based browser:
$('#profileurl').keyup(function(e) {
$("#url-displayname").html($(this).val());
});
Updated jsFiddle: http://jsfiddle.net/pQ3j9/3/
For the second question, if you wish to maintain characters and not have them parsed as html entities then you should do this instead :
$('#profileurl').keyup(function(key) {
$("#url-displayname").text($(this).val());
});
Check it out at - http://jsfiddle.net/dhruvasagar/pQ3j9/6/
You can bind multiple events with bind
http://jsfiddle.net/dwick/DszV9/

JQuery: Finding the Object that created a DOM Element

So I've been working on this all day and I can't figure out how to get it to work. I have a table with TD's filled with content which is drawn from a database using a JQuery "getJSON" command. I have an event handler set-up so that when you double click a TD element, its contents become a INPUT element with the default value of the enclosing TD's previous contents.
The INPUT element is created inside a Javascript object named "Input" like so:
var Input = function() {
var obj = this;
obj.docElement = $('<input/>').attr('type', 'text').val(obj.defaultValue);
}
All of this is working so far. My problem is, I want the user to be able to hit the RETURN key while the INPUT is selected to signify they've finished editing that field. I've tried something like the following:
$(obj.docElement).bind('keydown', function(e) {
if(e.which == 13) {
// do something
}
}
This works fine for the first time you edit a field; however, if you edit a field multiple times it stops working. Also if you randomly double click TD's eventually it breaks. I tested it and determined that the INPUT element stops registering any type event, as if the "bind" no longer existed on it.
I've done lots of googling and determined that the regular JQuery "bind" handler placed on an INPUT element is unreliable. Therefore I decided to attach the event handler to the document object instead using the following:
$(document).bind('keydown', function(e) {
// do something
}
I know I can use "e.target" to get the target element that the action is executed on (and this works for me, e.target correctly refers to the INPUT element).
My question is, how do I get the object that created the INPUT element in the first place? I need to be able to execute functions contained within the corresponding "Input"
class that was used to create the INPUT element. I need to call these functions from within the "$(document).bind" function. So basically I need to be able to get an INPUT element's parent/creator Input object.
If I haven't explained anything clearly enough, just let me know. Any help in this matter would be greatly appreciated! I'm also open to suggestions for alternative methods (other than using "$(document).bind").
Thanks!
I think I understand the problem ...
You can traverse the DOM to find the parent document element, but that's not what you mean, right? You want the parent script element that has a bunch of logic that operates on the element.
I suspect that it is probably easiest to provide some sort of reference to the parent when the input element is created ... pass this to the event handler, or set it in a globally accessible location (like a current_element_parent var).
I agree with tobyhede. You can either add a custom attribute to the INPUT element that refers back to the parent, or keep a map in memory that maps the dynamically created INPUT element to the parent that created it. When you trap the Return key, simply remove the relationship from the map so it can be added again if the user clicks it again.

Categories

Resources