I am trying to do something really simple using only Javascript (not JQuery).
Basically, I want to use a checkbox to toggle the text in a textarea. So if the checkbox is unchecked I want it to say "Hello" in the textarea. If the checkbox is checked, the textarea should say "Goodbye".
I'm just getting started with Javascript, so any help would be appreciated.
Thanks
Here is the code:
var myswitch = document.getElementsByTagName("myonoffswitch");
var mytextarea= document.getElementsByTagName("mytextarea");
myswitch.onchange = function(){
if(this.checked){
mytextarea.value = "Hello"
}else{
mytextarea.value = "Goodbye"
}
}
If your controls are in a form, you can do something really simple like:
<form>
<textarea name="ta"></textarea>
<input type="checkbox" onclick="
this.form.ta.value = this.checked? 'Hello':'Goodbye';
">
</form>
Note that using the change event with a checkbox means that in some browsers, the event won't be dispatched until the checkbox loses focus, so better to use the click event.
You should be using document.getElementById instead of getElementsByTagName
I can't tell from your code snippet if you've wrapped your code in an onload function. This is required in situations where your DOM elements are not loaded in the HTML at the time your javascript is running
Here's an example
window.onload = function () {
var myswitch = document.getElementById("myonoffswitch");
var mytextarea = document.getElementById("mytextarea");
myswitch.onchange = function () {
if (this.checked) {
mytextarea.value = "Hello";
} else {
mytextarea.value = "Goodbye";
}
}
//code here
}
And a fiddle is available here: http://jsfiddle.net/C4jVG/
I've tried something. This should work for you
HTML
<input type="checkbox" id="myonoffswitch">Switch</input>
<textarea id="mytextarea" cols="30" rows="10"></textarea>
Javascript
function fillText() {
var myswitch = document.getElementById("myonoffswitch");
var mytextarea= document.getElementById("mytextarea");
myswitch.onchange = function(){
if(this.checked){
mytextarea.value = "Hello"
}else{
mytextarea.value = "Goodbye"
}
}
}
window.onload = fillText;
Just try replacing getElementsByTagName in your code with getElementById this will solve your problem.
Related
I have an element on the page that looks like:
<textarea id="note-content" rows="4"></textarea>
when I try to write some jQuery to add some text to it:
$('#note-content').val('hi')
The button to "submit" the value is still greyed out.
I've tried
function setKeywordText(text) {
var el = document.getElementById("note-content");
el.value = text;
var evt = document.createEvent("Events");
evt.initEvent("change", true, true);
el.dispatchEvent(evt);
}
setKeywordText("test")
as a way to "simulate" sending keystrokes to the browser, but that doesn't seem to work either.
any thoughts?
You can do that by javascript
<script>
function changetext(){
document.getElementById("note-content").value = "hi";
}
<script>
It should def. work. Plus what exactly did you mean by browser simulation?
Am i missing something?
It appears this problem is occurring because your button is disabled.
To solve this you'd remove the disabled attribute using jQuery.fn.removeAttr, like this:
$("#button-id").removeAttr("disabled");
Add this solution it to your vanilla JavaScript code, like this:
function setKeywordText(text) {
// disable button
var btn = document.getElementById("button-id");
btn.disabled = false;
// set input value
var el = document.getElementById("note-content");
el.value = text;
// create and dispatch the event
var evt = document.createEvent("Events");
evt.initEvent("change", true, true);
el.dispatchEvent(evt);
}
// run the function
setKeywordText("test");
Good luck.
I am new to JS. I am creating a button and I want the button to toggle what it says. I can get it to fire once, but then it won't fire again unless i refresh the page. What am I doing wrong? I'm sure its simple.
JS function:
<script type="text/javascript">
function fullscreen(){
var elem = document.getElementById("button1");
if (elem.value=="Maximize"){
elem.value = "Minimize";
}else {
elem.value = "Maximize";}
}
</script>
in the body of the page is:
<div>
<input type="button" id="button1" value="Minimize" onclick='fullscreen()'>
</div>
What I expect is the text of the button will switch when the variable is passed through the if statement. I can get it to change from "minimize" to "maximize" onclick, but the second click does nothing.
Hey i did put alert and your code is working fine. You can even see this in your developer console. Also you should put === instead of == for comparing to string.
There should be other problem i think.
function fullscreen(){
var elem = document.getElementById("button1");
if (elem.value ==="Maximize"){
alert('hi');
elem.value = "Minimize";
} else {
alert('hello');
elem.value = "Maximize";}
}
I have to validate via javascript, no jquery, if the user is currently changing an input slider. I can find nothing in slider reference.
any tips are welcome thanks
var slider = document.getElementById('slider');
var output = document.getElementById('output');
var isSliding = false;
slider.addEventListener('input', function () {
isSliding = true;
output.innerHTML = isSliding;
});
slider.addEventListener('mouseup', function () {
isSliding = false;
output.innerHTML = isSliding;
});
jsfiddle: http://jsfiddle.net/z9bkurra/
If I understand you correctly, you could do something like this.
As your 'slider' is an <input type="range"/> you can listen for change-events.
document.getElementById('mySlider').addEventListener('change', function () {...});
See http://devdocs.io/dom_events/change "The change event is fired for <input>, <select>, and <textarea> elements when a change to the element's value"
Much like when typing a comment on Facebook and you hit #username, it reacts to that, letting you choose a username inline.
Using jQuery, how would one go about hooking up an event listener for [text:1]. I want an event to fire when the user has entered [text: into a text field.
Zurb created a textchange plugin that will help. See their "Validate Text" example towards the bottom, i believe its almost exactly what you're looking for..
http://www.zurb.com/playground/jquery-text-change-custom-event
use keyup function to trigger. Split all the string and check it.
[UPDATE]: More Improved Version
<script>
var totalcount=0;
$(function (){
$('#text').keyup(
function (){
var arr = $(this).val().split(" ");
var matchitems = count('hello', arr);
//console.log(matchitems);
if(matchitems > totalcount){
alert('hello');
totalcount = matchitems;
}
if(matchitems < totalcount)
{
totalcount = matchitems;
}
}
)
})
function count(value, array)
{
var j=0;
for(var i=0;i<array.length;i++)
{
if(array[i] == "hello"){
j++;
}
}
return j;
}
</script>
<input type="text" id="text" />
})
</script>
<input type="text" id="text" />
Using keyup like #experimentX mentioned is the way you want to go b/c then you'll know that your user has inputed value then. However, running a for loop would be extremely costly on every single keyup event. Instead, since you know the value you want already, you can use a preset regexp to search for your value:
<input type="text" id="text" value="" />
<script>
$(function () {
var $input = $('#text');
$input.keyup(function (e) {
var regexp = /\[text\:/i,
val = $(this).val();
if (regexp.test(val)) {
console.log('i have it: ', val);
}
});
});
</script>
Here are a couple additional scenarios on how you can write the actual regexp.
You want the string to be at the very beginning of the input: var regexp = /^\[text\:/i;
Building on the one above, but incorporate any amount of whitespace in front of the text you actually want: var regexp = /^\s+?\[text\:/i;
Is there a way to make a HTML select element call a function each time its selection has been changed programmatically?
Both IE and FF won't fire 'onchange' when the current selection in a select box is modified with javascript. Beside, the js function wich changes the selection is part of framework so I can't change it to trigger an onchange() at then end for example.
Here's an example:
<body>
<p>
<select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select>
<input type="button" onclick="test();" value="Add an option and select it." />
</p>
<script type="text/javascript">
var inc = 1;
var sel = document.getElementById('sel1');
function test() {
inc++;
var o = new Option('n'+inc, inc);
sel.options[sel.options.length] = o;
o.selected = true;
sel.selectedIndex = sel.options.length - 1;
}
function myfunction() {
document.title += '[CHANGED]';
}
</script>
</body>
Is there any way to make test() call myfunction() without changing test() (or adding an event on the button)?
Thanks.
If you can extend/modify the framework to give a hook/callback when they change the select options, it would be better (one way could be to use the dynamic capabilities of js to duck type it in?).
Failing that, there is an inefficient solution - polling. You could set up a setTimeout/setInteval call that polls the desired select option dom element, and fire off your own callback when it detects that something has changed.
as for the answer to your question
Is there any way to make test() call
myfunction() without changing test()
(or adding an event on the button)?
yes, by using jquery AOP http://plugins.jquery.com/project/AOP , it gives an easy-ish solution.
<body>
<p>
<select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select>
<input type="button" onclick="test();" value="Add an option and select it." />
</p>
<script type="text/javascript">
var inc = 1;
var sel = document.getElementById('sel1');
function test() {
inc++;
var o = new Option('n'+inc, inc);
sel.options[sel.options.length] = o;
o.selected = true;
sel.selectedIndex = sel.options.length - 1;
}
function myfunction() {
document.title += '[CHANGED]';
}
//change to aop.after if you want to call afterwards
jQuery.aop.before( {target: window, method: 'test'},
function() {
myfunctino();
}
);
</script>
</body>
Define your own change function that calls the framework function and then calls a
callback function.
e.g.:
function change(callback)
{
frameworkchange();
callback();
}
The answer is .... no.
The DOM only fires the onchange event as a result of user action not code. It does not provide any additional events to hook in this regard.
You will need to customise the framework or drop your requirement.
ahem...
you can access the event 'onpropertychange' it contains a property within the event arguments to identify which property was changed.
It detects both 'selectedIndex' and 'value' changes - simply case test 'propertyName' I'm currently working with the ASP.NET js framework here is some straight copy-paste code for that:
1) define handler:
this._selectionChangedHandler = null;
2) assign handler
this._selectionChangedHandler = Function.createDelegate(this, this._onSelectionChanged);
3) attach handler to event
$addHandler(element, "propertychange", this._selectionChangedHandler);
4) create function
_onSelectionChanged: function(ev) {
if (ev.rawEvent.propertyName == "selectedIndex")
alert('selection changed');
},
With JQuery, you could do something like
$(document).ready(function(){
$('#select-id').change(function(e){
e.preventDefault();
//get the value of the option selected using 'this'
var option_val = $(this).val();
if(option_val == "v1"){
//run your function here
}
return true;
});
});
This would detect the change programmatically and let you respond to each item changed