I want to change background colour when I click input - javascript

<input type="submit" value="Login" onclick="myFunction">
<!-- Project -->
<script>
function myFunction(){
document.getElementById("input[tpye="submit"]").style.backgroundColor="blue";
}
</script>

getElementById gets the element with that id. You're probably looking for querySelector instead, which will select the element that matches that selector:
function myFunction(){
document.querySelector("input[type='submit']").style.backgroundColor="blue";
}

You have done three mistakes in your code snippet
You have not given () to the function call
You have written incorrect spelling in the querySelector of "type" word
You are calling the getElementById() function but you have not given id to the input box
<input type="submit" value="Login" onclick="myFunction()">
<!-- Project -->
<script>
function myFunction(){
document.querySelector("input[type='submit']").style.backgroundColor="blue";
}
</script>

In the javascript function you are using 'getElementById' which means that it'll look for the DOM elements with the id you have provided, and the problem is you didn't provided any id.
You have to first give an id to the button
<button id="some_id">Click</button>
And then align your function in this way.
function myFunction(){ document.getElementById("some_id").style.backgroundColor="blue"; }

this is my solution to your problem. In your case you have some type of input, you need first to add an event listener to the input, which will execute some function on a specific event. In our case, we will execute the change color function.
This is a quick solution to your problem.
let button = document.getElementById('changecolor');
let input = document.getElementById('basic-input');
function changeBackground(){
// Change the background of the page
document.body.style.background = 'red';
// Change background of the button
button.style.background = 'blue';
}
button.addEventListener('click' , changeBackground);
input.addEventListener('click' , changeBackground);
<button id="changecolor">Change background</button>
<input type="text" placeholder="basic input" id="basic-input">

Related

Calling the click function for button in jQuery

I am very new to jQuery and HTML. I am trying to create a button in html that uses jQuery to make the button to prompt alert message when clicked (rather than using onclick in html). In other words, I would like to use the jquery to call up the click function for the button and then return a pop up message.
I have my input type as "button" and my value as "Check" for my button in html.
Here's my code in javascript
$(document).ready(function(){
$("button").click(function(){
alert("Pop Out");
});
but nothing is showing up
Here's a fiddle to my code
http://jsfiddle.net/0ynbv233/8/
I have my input type as "button"
Like this?
<input type="button" />
In that case, this won't work:
$("button")
That selector is looking for button elements, not input elements. You can change the element:
<button />
or you can change the selector:
$('input[type="button"]')
I did what you have done and it worked for me.
Here is what my code was.
$(function(){
$("button").click(function () {
alert("Pop Out");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button>Click Me</button>
Hope you figure out what you are doing wrong.

How can I set focus on an element in an HTML form using JavaScript?

I have a web form with a text box in it. How do I go about setting focus to the text box by default?
Something like this:
<body onload='setFocusToTextBox()'>
so can anybody help me with it? I don't know how to set focus to the text box with JavaScript.
<script>
function setFocusToTextBox(){
//What to do here
}
</script>
Do this.
If your element is something like this..
<input type="text" id="mytext"/>
Your script would be
<script>
function setFocusToTextBox(){
document.getElementById("mytext").focus();
}
</script>
For what it's worth, you can use the autofocus attribute on HTML5 compatible browsers. Works even on IE as of version 10.
<input name="myinput" value="whatever" autofocus />
Usually when we focus on a textbox, we should also scroll into view
function setFocusToTextBox(){
var textbox = document.getElementById("yourtextbox");
textbox.focus();
textbox.scrollIntoView();
}
Check if it helps.
If your code is:
<input type="text" id="mytext"/>
And If you are using JQuery, You can use this too:
<script>
function setFocusToTextBox(){
$("#mytext").focus();
}
</script>
Keep in mind that you must draw the input first $(document).ready()
For plain Javascript, try the following:
window.onload = function() {
document.getElementById("TextBoxName").focus();
};
I used to just use this:
<html>
<head>
<script type="text/javascript">
function focusFieldOne() {
document.FormName.FieldName.focus();
}
</script>
</head>
<body onLoad="focusFieldOne();">
<form name="FormName">
Field <input type="text" name="FieldName">
</form>
</body>
</html>
That said, you can just use the autofocus attribute in HTML 5.
Please note: I wanted to update this old thread showing the example asked plus the newer, easier update for those still reading this. ;)
As mentioned earlier, document.forms works too.
function setFocusToTextBox( _element ) {
document.forms[ 'myFormName' ].elements[ _element ].focus();
}
setFocusToTextBox( 0 );
// sets focus on first element of the form
window.onload is to put focus initially
onblur is to put focus while you click outside of the textarea,or avoid text area
blur
<textarea id="focus"></textarea>
<script>
var mytexarea=document.getElementById("focus");
window.onload=function()
{
mytexarea.focus();
}
</script>
If your <input> or <textarea> has attribute id=mytext then use
mytext.focus();
function setFocusToTextBox() {
mytext.focus();
}
<body onload='setFocusToTextBox()'>
<form>
<input type="text" id="mytext"/>
</form>
</body>
this example worked for me
$(document).ready(function () {
document.getElementById('TextBox').focus();
}
Try This:
$('.modal').on('shown.bs.modal', function () {
setTimeout(function() {
$("input#yourFieldId").addClass('modal-primary-focus').focus();
},
500);
});
Thought of sharing some edge cases for this subject.
If your content is reloading (example dynamic DOM loading results from API and setting focus on first item of results) adding attribute autofocus will not be your solution, it works only on first load, second DOM change will not work but works fine in static DOM or single page load. If you have Dynamic component loading data simple .focus() will fail due to triggering focus on element not created yet by the time focus() is or blur not complete yet by DOM. For this case expected is to add delay time (setTimeout function) to give a time for focus to apply to new created or recreated element in DOM. My case was to load data from API and get focus on first result.
Adding var el = document.getElementById(focusId); el.focus(); solved the issue so DOM completes blur without adding delay.
<input type="text" class="word"> //html code
let theinput = document.querySelector(".word"); //Get the input
theinput.focus(); // focus on input

jQuery how to get input from a form?

<script>
$(function() {
var first_name = $('#content').find('input[name="first_name"]').val();
console.log(first_name);
})
</script>
<div id="content">
<form name="info">
First Name: <input type="text" id="first_name" name="first_name"><input type="submit" id="button">
</form>
</div>
Does not print name in console, what am I doing wrong here?
The problem right now is that the code you've written is executed immediately when the page loads.
From the way your code looks, it looks like you actually want the form's button to do the console log.
I've altered your code a bit, but here's how you'd:
Select the Form and the Input
Declare the variable out of the scope
Bind onto the form's submit event
Prevent it from actually submitting
And logging to console per your example
Altered code below:
<script>
$(function() {
// Save a reference to the input
var input = $("input[name=first_name]"),
// Get the form itself
form = $("form[name=info]"),
// Storage for your first_name outside of the scope
first_name = false;
// Bind to the submit event on the form
form.bind('submit', function() {
// Set the first_name to the input's value
first_name = input.val();
// Log it out (per your example)
console.log(first_name);
// Return false to prevent the form from posting
return false;
});
});
</script>
<div id="content">
<form name="info">
First Name:
<input type="text" id="first_name" name="first_name">
<input type="submit" id="button">
</form>
</div>
I'm not saying this is the best way to handle whatever you're attempting to do with the form, realistically you shouldn't need an ID on the button, and probably would want to replace the NAME on the form with an ID for the selector. Also using an ID selector to get the input would be recommended as well, as ID selectors are faster than [name=something] selectors. (Thanks gnarf for the comment!)
The variable scoping is also probably somewhat strange in your example, but the above code should be good for learning :)
The method as you've written it only runs once, after the page loads. At that point the input element doesn't contain a value (i.e. $("#first_name").text() == ''). You can bind the logging statement to the keyup event of the element, to see the text that's being entered into it.
$(function() {
// this code only runs once
var first_name = $('#content').find('input[name="first_name"]').val();
console.log(first_name);
$('#first_name').keyup(function() {
// this code fires everytime a key is released on the element
console.log($(this).val());
});
})
Demo on plnkr
Here is the JSFiddle for your code.
<div id="content">
<form name="info">
First Name: <input type="text" id="first_name" name="first_name" value="something">
<input type="submit" id="button">
</form>
</div>
$('#content form').on('submit', function () {
console.log($('#content').find('input[name="first_name"]').val());
});
'Something' is the default value.' Try other words in the text box and you will see the new value in console.
As per your code, you are getting correct results.
Your defined function is never called because you have not attached any events to it.
I have modified your code and you can check it working here
$(document).ready(function(){
$("#first_name").focusout(function(){
var first_name = $(this).val();
alert(first_name);
});
});
$('#content form').on('submit', function () {
console.log(
$(this).find('input[name="first_name"]').val()
);
return false;
});
edit: you must run your jQuery selection after you have inputted something into the input field. Right now when you run it, it is empty
edit: try using this 'on' from the jQuery docs
http://api.jquery.com/on/
$('#content form').on('submit', function () {
console.log($('#content').find('input[name="first_name"]').val(););
}

How do I create a text box with a submit button that performs a callback on click to a javascript function using js or jQuery?

I'm new to javascript and am having a hard time finding the answer to this. Any help is appreciated.
If you had the following HTML:
<input type="text" />
<input id="button" type="button" value="Click Me" />
You can bind a function to be executed when a click event fires on that button like this:
$(function() {
$('#button').click(function() {
// Do logic here
});
});
Creating it all on the fly
You can insert the previous HTML into your document using jQuery. First select another element in the DOM which locates where you wish to insert the HTML:
$('#someElement')
Then you can use any of the jQuery insertion methods in order to inject some HTML of your own:
$('#someElement')
.append('<input type="text" />')
.append('<input id="button" type="button" value="Click Me" />');
Now that your elements are in the DOM, you can select them and bind a callback to the click event in the normal way:
$('#button').click(function() {
// Do logic here
});
the html :
<textarea id="txt"></textarea><input type="button" id="button">submit</input>
and the js:
var d = document.getElementById('button');// identifying the button
function myFunction(){
var text = document.getElementById('txt').value;//getting the user's input
// and whatever you want to do with the user's input
}
d.addEventListener('click',myFunction,false);//attaching myFunction to be called on the button click`
If you use jQuery, the syntax is a bit simpler :
$('#button').click(myFunction);
// or
$('#button').click(function(){
var text = $('#txt').val();
//and again your logic here
});

Using Javascript to change the method/function an HTML element calls

I was wondering if its possible to use Javascript to change the function/method that an HTML element calls.
Example:
<input type="button" id="some_id" name="some_name" value="A Button" onclick="someFunction()" />
I now want to use Javascript to change the method/function called on the onclick event to another function has displayed below.
<input type="button" id="some_id" name="some_name" value="A Button" onclick="anotherFunction()" />
I tried using innerHTML, and when I checked the generated HTML, it actually changed the value of the onclick event in the button, but when I click the button, the method is not called.
You can assign a function object directly to the onclick field of the element. For example,
var inp = document.getElementById( 'some_id' );
inp.onclick = anotherFunction;
Using jQuery you could do:
$('#some_id').unbind('click');
$('#some_id').click(function () {
anotherFunction();
});

Categories

Resources