use button to write text to the page - javascript

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.

Related

Jquery - Stop Event of Other Class

This is what I want
Jquery:
$("body").on('click','.js-validate-url',function(){
var url = $(".url").val();
if(url==""){
// STOP WORKING OF .js-loader click
// I want if url is empty it should not alert
}else{
//OK
// and here it should work fine
// it should alert
}
});
$("body").on('click','.js-loader',function(){
alert();
});
HTML
<form>
<input class="url">
<button class="js-loader js-validate-url"></button>
</form>
<form>
<button class="js-loader"></button>
</form>
Why I am doing this
Upper class is different for all buttons
But loader class is same for all buttons it shows loader inside clicked button
I found
e.stopPopagation();
But that works if I use it in loader click callback But I want to stop when button is clicked and url is empty
Cannot check url=="" inside loader click call back cause it is same for all button i dont want to check on other buttons click too so checking for single button
I would recommend using classes to check for condition.
$("body").on('click','.js-loader',function(){
var _this = $(this)
if(_this.hasClass('js-loader') && _this.hasClass('js-validate-url')){
// if both classes js-loader, js-validate-url are present on button
alert()
}else{
alert("js-loader") // if only js-loader present on button
}
});
I'm not sure if I understand what you are trying to do, but I guess you can merge your events into a single one and use an external function only when it met a condition.
You could also use removeEventListener but I don't believe you need it for your problem.
var myFunction = function(){
alert('loader');
};
$("body").on('click','.js-validate-url',function(){
var url = $(".url").val();
if (url){ alert('validate: '+url); }
else myFunction();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="google.com" class="url"/>
<button class="js-validate-url js-loader">Bt1</button>
<button class="js-loader">Bt2</button>
This is what I did and is working fine as per my requirement
$("body").on('click','.js-validate-url',function(){
var url = $(".url").val();
if(url==""){
// STOP WORKING OF .js-loader click
// I want if url is empty it should not alert
}else{
$(this).removeClass("js-diable");
//OK
// and here it should work fine
// it should alert
}
});
$("body").on('click','.js-loader',function(){
if($(this).hasClass('js-scud-disabled')){
//NOTHING TO DO
}else{
alert();
}
});
HTML
<form>
<input class="url">
<button class="js-loader js-validate-url js-disable"></button>
</form>
<form>
<button class="js-loader"></button>
</form>
$("body").on('click','.js-loader',function(){
if($(this).hasClass('js-loader js-validate-url')){
alert();
} else {
if(url==""){
} else {
}
}
});

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.

Eventlistner on Checkbox should give user a prompt

I have a checkbox on the webpage and I want that when the check box is ticked a prompt should come with a 'message and YES\NO button'. Clicking YES should take the user to the next website and clicking NO just close the prompt.
How can this be done using Javascript.How will the program know if the checkbox is yicked or not? I read using addeventlistner but i dont know how to use it. Can someone share an example.
You can use addEventListener to bind event
document.getElementById('testcb').addEventListener('change', function () {
if (this.checked) {
if (confirm('Really Take me to new loaction?')) {
alert("Take me to new loaction");
//window.location.href = newURL;
}
}
}, false);
DEMO
I would recommend using a library, like jQuery, and you could do somtehing like this
HTML:
<input type="checkbox" name="testcb" id="testcb" />
JavaScript:
$(function() {
$('#testcb').click(function() {
if (this.checked) {
if (confirm('Really?'))
window.location.href = newURL;
}
});
});
Careful with addEventListener : it will not work with IE 8 and below, and 'change' event is buggy in the same browser (IE8-) (http://www.quirksmode.org/dom/events/change.html)
Add a JavaScript function on check box event ,
HTML
<input id="chk" onclick="doSomething()" type="checkbox">
javascript function :
function doSomething()
{
var x = document.getElementById("chk").checked;
if (x)
{ var conf = confirm("checkbox is checked, proceed ?");
if (conf == true) {
window.location = "http://www.google.com";
}
}
}
Don't forget to add reference of jQuery (you can add from googleAPI)

JavaScript button function swap

What I am trying to do is following:
I have an input type button and I want to replace it's function on first click.
<input type="submit" class="submit-button" value="Submit" name="boom" />
So a [button] that serves for submit, I wanna show alert with some jquery plugins but lets do it here with normal javascript alert (default window).
So on first click it will be
alert('Something');
And on second click it will be default function (submit).
How can I achieve something like this?
Of course if button is clicked once, and then page reloaded, it will show same alert again on first button click.
Use one().
Attach a handler to an event for the elements. The handler is executed at most once per element.
Example:
$(".submit-button").one("click", function(e) {
// will only run on first click of element
e.preventDefault();
alert("Something");
});
Try this:
<script type="text/javascript">
var clicked = false;
function btnClick(e) {
if(clicked === false) {
alert('Something');
clicked = true;
e.preventDefault();
return true;
} else {
return false;
}
}
</script>
<input type="submit" onclick="btnClick(event)" class="submit-button" value="Submit" name="boom" />

Knowing the last clicked textbox via 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

Categories