I'm trying to figure out how to set the input value of a text field to the value of it's title when the page loads, as a way to show placeholder text. I'm using an HTML4 Strict doctype. I don't want to store the placeholder text in the input value, because I don't want people without javascript to have to delete the text before typing. I want it to be added with javascript, and then removed when the input gains focus. I have the focus() and blur() methods working, but I can't figure out how to write the initial pageload function to pass the input's title to the val() function.
I currently have this code:
// This doesn't work, it grabs the page title:
$('#item-search').val(this.title);
// Works:
$('#item-search').focus(function() {
if (this.value == this.title) {
this.value = '';
}
});
// Works:
$('#item-search').blur(function() {
if (this.value == '') {
this.value = this.title;
}
});
Just to add another variation, .val() can accept a function as its parameter, fixing your this issues:
$('#item-search').val(function () {
return this.title;
});
this refers to the current scope. In your first example, its referring to document.
You may want.
$('#item-search').val($('#item-search').attr('title'));
Even better:
var $itemSearch = $('#item-search');
$itemSearch.val($itemSearch.attr('title'));
$('#item-search').val(this.title);
In this line this refer the document(html) and set the <title>. To accomplish you job do this:
$('#item-search').val($('#item-search').attr('title'));
Try this:
$('#item-search').val($('#item-search').attr('title'));
Please try this.
$('#item-search').val($("#item-search").attr("title"));
Related
I want to be able to change multiple text inputs (but not all) by class, but can't seem to get it working.
Any ideas?
Basically I have multiple reset buttons on the same page I'd like to have 'resetting' the value of the targeted text inputs to nothing.
Here's the code:
$(".reset").on('click', function() {
document.getElementsByClassName('input-1').value = '';
});
It works fine when using getElementById, but I would rather minimise the code and not have to repeat it each time for every text input.
You are already using jQuery, so just use
$(".reset").on('click', function() {
$('.input-1').val('');
});
Notice the . before the class name, same as in .reset.
If you want to use vanilla JavaScript, you have to loop through the HTMLCollection returned by getElementsByClassName:
$(".reset").on('click', function() {
Array.from(document.getElementsByClassName('input-1')).forEach(el => el.value = '');
});
jQuery does that automatically for you.
You can use an special selector for this job:
let inputs = [... document.querySelectorAll("[class^='input-']")];
inputs.forEach(i => i.value = "");
class^= will return all the elements containing class attribute starting with "input".
I would like to make a script that, when the text of a certain paragraph change, start a certain function, I tried the follow but i don't think the method change() works for a paragraph
$("#myParagraph").change(function(){......})
You would wrap that tag or "paragraph" in a container, and bind that container to a event possibly. You could also look into using the length of the "text" property. During this triggered event, check that the state is different. I can write an example if you need one. One place to look at is the
//global variable. Store in hidden field if you would like.
var currentVal = $('element').text();
$('element').bind("DOMSubtreeModified",function(){
var newVal = $(element).text();
if(currentVal != newVal)
{
//call function here.
}
});
This is basic and very simple, but to give you the idea.
I'm a Jquery noob, very much in the learning stage.
This is my fiddle:
http://jsfiddle.net/4tjof34d/
(Double click any of the three dots to get a textbox in the above fiddle, then enter a value in that box and press enter)
As you can see it works but how do I get the id and value when the user puts a new value into the textbox?
Basically, I need to get the value in to something like this:
var theId = $(this)id;
var newValue = $(this)value;
// console.log(theId+" "+newValue+ " "+savedData);
so I can make an AJAX call to update the DB with the new value/s.
If you could put a comment in the code as well, for example:
// ajax call here
that would be appreciated as well!
I notice you're using jQuery, but it's actually easier to get the values without it:
var showText = function() {
console.log(this.id);
console.log(this.value);
}
However, to get the values with jQuery, simply use attr() and val():
var showText = function() {
// Cache $(this) since we're
// using it more than once.
var $this = $(this)
console.log($this.attr('id'))
console.log($this.val())
}
You can use plain JavaScript as follows:
var theId = this.id; //or $(this).attr('id');
and
var newValue = this.value; //or $(this).val();
THE HOW & WHERE
var showText = function () {
$(this).hide();//show text
$(this.nextElementSibling).show();//hide input
$.ajax({
url: '....',
data: {id: this.id, value: this.value},
....
});
};
With Jquery for any input element you can use .val() function . So your syntax will be like
$("selector").val();
Now the syntax for this selector will keep on varying. For ex - if you want to get value for any specific id for an input element you use "#". So if you have an input field with an id of "testId" you will be doing
<input type="text" id="testId" class ="testClass"/>
$("#testId").val();
In place of id if you want the same value but with the help of class attribute you will be doing
$(".testClass").val();
Now if you have some other fields other than input fields you should ideally be using .text() for them.
So if you have a div with an id of testDiv you just need to do
<div id ="testDiv" class="testDivClass">Test</div>
$("#testDiv").text();
$(".testDivClass").text();
Just an advice, since you are learning jQuery right now refrain yourself from using hybrid things (mixing core javascript) just for the sake of finishing all the work. This way you may have to spend some time in learning things but ultimately you will be learning things in much better way
Hope this be of some help.
Happy Learning
use .attr() and .val() to get attribute and value:
$(this).attr('id');
and
$(this).val();
So, I created the code where user clicks on the button and then jQuery reads the value inside the input text and I stored that in variable. But if I want to use that variable and append that value to the element, jQuery returns undefined is not a function and it doesn't work. Here is the fiddle:
Fiddle: http://jsfiddle.net/2cf1y8Lc/1/
Is this about adding menu div element form text field. Here is update of fiddle code you send hope it helps.
$('#btnSubmit').on('click',function(e){
var newMenu = $('#add_list').val();
var elem = '<li><span class="glyphicon glyphicon-briefcase"></span> '+newMenu+'</li>';
$('.nav-pills.nav li').last().append(elem);
});
http://jsfiddle.net/2cf1y8Lc/2/
One possible reason may be if the value from text input is null and you are using parseInt() or parseFloat() on this variable. So check its value before use
$("#btn").click(function(e){
var myvar= $("#myhiddenfld").val();
if(myvar=="") myvar=0;
else myvar=parseInt(myvar);
$("#storeinput").val(myvar);
//or use your append code here as you like
})
Does anyone know how to do replace multiple text by clicking a button with jQuery?
I've built a website that displays some text/data eg; "£100.00", but I what I need is to be able to 'replace' those monetary values with "£XXX.XX" with a 'Hide' button like you get on some banking websites. For example one web page has:
£100.00, £200.00, £130.00 etc etc..
...so when a user presses the Hide button, all of the numbers on the page turn to £XXX.XX. Ideally, the button should then display "Show" instead of "Hide" and switch back when toggled.
This is for a static dummy site, so no data base.
I suspect this is best handled with jQuery?
Thanks for your time,
D.
Case 1: Controlled Input
Assuming you can at least wrap all monetary values with something like this:
<span class="money-value">£200.00</span>
<span class="money-value">£300.50</span>
And that you can add button declared with:
<button id="secret-button">hide</button>
Then you could have some jQuery code doing this:
/**
* Simple search and replace version.
*/
$(function() {
$("#secret-button").click(function() {
$(".money-value").html($(".money-value").html().replace(/[0-9]/g,"X"));
});
});
or a more advanced one with:
/**
* Complet version.
*
* 1) on button click, if asking to hide:
* 1.1) iterate over all entries, save their text, and replace it with markers
* 1.2) toggle the button's text to "show"
* 2) on button click, if asking to show:
* 2.1) iterate over all entries, restore previous text
* 2.2) clear the hidden store
* 2.3) toggle the button's text to "hide"
*/
$(function() {
var hiddenStore = [];
$("#secret-button").click(function() {
if ($(this).html() == "hide") {
$(".money-value").each(function () {
var text = $(this).html();
hiddenStore.push(text);
$(this).html(text.replace(/[0-9]/g,"X"));
});
$(this).html("show");
} else {
$(".money-value").each(function (i) {
var text = hiddenStore[i];
$(this).html(text);
});
hiddenStore = [];
$(this).html("hide");
}
});
});
Complete solution is here: See here: http://jsfiddle.net/u79FV/
Notes:
this won't work for input field values
this assumes your text entries have been marked as shown above
Does what you want with the button's changing state.
Saves the values and puts them back.
Meant to work even if new fields are added dynamically.
Shankar Sangoli's answer uses a different way of saving the stored data, which you could as well consider (using the jQuery .data() method).
you may want to switch the button to an <input type="button" /> tag, in which case you'd use .val() instead of .html() to toggle its text.
Case 2: Uncontrolled Input
Assuming you don't have control over where the values may show up, then you need to do something a bit more complicated, which is to look in the whole page for something that would look like a currency format. I'd advise against it.
But, the jQuery Highlight plugin could be something to look at, as its code does something similar (in that it searches for pieces of code to modify), and you could then reuse some of solution 1 to make it fit your purpose.
That would be harder to design in a fool-proof fashion though.
You could use a regular expression:
var expression = /\d{1}/g;
var newString = myString.replace(expression,"X");
Then just dump newString into whatever control you need it to appear in.
Edit:
A jQuery idea for something like this would be to give all of the controls that have these numbers a common class identifier to make them easy to grab with the selector:
$(".numbers").each(function() {
$(this).text($(this).text().replace(/\d{1}/g, "X"));
}
... more readable ...
$(".numbers").each(function() {
var text = $(this).text();
var newText = text.replace(/\d{1}/g, "X");
$(this).text(newText);
}
If your markup is something like this you can try this.
<span>£1000.00</span><span class="showhide">Hide</span>
JS
$('.showhide').click(function(){
var $this = $(this);
var $prev = $this.prev();
if(!$prev.data('originalvalue')){
$prev.data('originalvalue', $prev.text());
}
if($this.text() == 'Hide'){
$this.prev().text($prev.data('originalvalue').replace(/\d{1}/g,"X"));
$this.text('Show');
}
else{
$prev.text($prev.data('originalvalue'));
$this.text('Hide');
}
});
In the above code I am basically storing the original value using jQuery data method within the span element itself which is used to display the actual value.
Once you click on Hide, get the previous span using prev() method and set its text with original value replacing all the numbers in it by X. Then change the link text from Hide to Show.
Next when you click on Show get the previous span using prev() method and set its text with the original value and change the link text from Show to Hide.
References: .prev(), .data()
$('#yourButton').click(function(){
var saveText = $('body').text();
$(this).data('oldText', saveText);
if ($(this).text() == "Hide"){
$('body').text($('body').text().replace(/\d{1}/, "X"));
$(this).text('Show');
}
else{
$('body').text($(this).data('oldText'));
$(this).text('Hide');
}
});
This is kind of a complicated problem actually. You will need to be able to save the state of the text when its in number form so you will be able to toggle back and forth. The above code is untested but hopefully it will give you an idea what you need to do.
function toggleMoney() {
$('.money').each(function() {
var $$ = $(this), t = $$.text();
$$.text($$.data('t') || t.replace(/\d/g, 'X')).data('t', t);
});
$('#toggleButton').text($('.money').text().match(/\d/) ? 'hide' : 'show');
}
http://jsfiddle.net/DF88B/2/