I have a dynamic button with looping and I have the onclick attribute function, like below :
for (var j=0; j<= 1; j++){
btndisplay= document.createElement("input");
btndisplay.setAttribute("type", "button");
btndisplay.setAttribute("style","height:80px;width:60px");
btndisplay.setAttribute("onclick", "myFunction"+ (j+1) +"(this.name)");
document.getElementById('divButtons'+(j+1)).appendChild(btndisplay);
}
How to simplify many functions as below, into a single function?
function myFunction1(name)
{
if (document.getElementById('value1').innerHTML==""){
document.getElementById('value1').innerHTML = name;
}
}
function myFunction2(name)
{
if (document.getElementById('value2').innerHTML==""){
document.getElementById('value2').innerHTML = name;
}
Use another parameter, one for the name and another for the id:
function myFunction(id, name)
{
if ( document.getElementById(id).innerHTML=="" )
document.getElementById(id).innerHTML = name;
}
you have created:
<input type="button" onclick="myFunction(this)">
<input...
...
the Function is:
function myFunction (that) {
if(that.innerHTML === "") {
that.innerHTML = that.name;
}
}
Related
Having this issue with trying to use addEventListener where the event I use does not read me clicking the button I have:
<input type="button" name="rps_button" id="rps_button" class="box_styled" value="Try Your Luck!">
<label for="rps_button"></label>
//The purpose of this JS file is for Rock Paper Scissors.
/*
1- Grab User input & store into variable userAnswer.
2- Get Computer input & store into variable compAnswer.
3- Switch case to compare both answers & give results.
Loop to check which one is checked
*/
var rps = document.getElementById("rps_button");
var rps_radio = document.querySelectorAll('input[name="rps"]');
var userAnswer = "";
var compAnswer = "";
rps.addEventListener('click', console.log("Clicked!"));
function init(e) {
uSer(userAnswer);
console.log(userAnswer);
}//[End] of Function
function uSer(userAnswer) {
console.log(rps_radio.value);
for (var i = 0; i < rps_radio.length; i++) {
if (rps_radio[i].checked) {
userAnswer = rps_radio[i];
}//[End] of if
}//[End] of Loop
console.log(userAnswer);
return userAnswer;
}//[End] of Function
What am I missing here with this Even issue?
You have implemented addEventListener incorrectly
This
rps.addEventListener('click', console.log("Clicked!"));
Should be this
rps.addEventListener('click', () => {
console.log("Clicked!");
});
you could also use a regular function instead of an arrow function
rps.addEventListener('click', function() {
console.log("Clicked!");
});
so basically your event was firing.. but the callback function wasnt implemented correctly, thus why you never got your console.log()
below is working example
const rps = document.getElementById("rps_button");
const rps_radio = document.querySelectorAll('input[name="rps"]');
let userAnswer = "";
let compAnswer = "";
rps.addEventListener('click', () => {
console.log('clicked');
});
function init(e) {
uSer(userAnswer);
console.log(userAnswer);
}
function uSer(userAnswer) {
console.log(rps_radio.value);
for (var i = 0; i < rps_radio.length; i++) {
if (rps_radio[i].checked) {
userAnswer = rps_radio[i];
}
}
console.log(userAnswer);
return userAnswer;
}
<input type="button" name="rps_button" id="rps_button" class="box_styled" value="Try Your Luck!">
<label for="rps_button"></label>
I created a form dynamically with javascript. Now I have to add validations on the form (only mandatory validations) on click of the button which is also dynamically created. Now the issue I am facing is that whenever I try to add addEventListener on the button exactly after creating it, it is giving me error.
(
function init() {
console.log("div created");
// create a new div element
var newDiv = document.createElement("div");
newDiv.id = "registration_form";
var createForm = document.createElement("form");
newDiv.appendChild(createForm);
var heading = document.createElement("h2");
heading.innerHTML = "Registration Form";
createForm.appendChild(heading);
var linebreak = document.createElement('br');
createForm.appendChild(linebreak);
createElement(createForm, 'label','','','Name: ');
createElement(createForm, 'text', 'dname', '','');
createSpanTag(createForm,'nameError');
breakTag(createForm);breakTag(createForm);
createElement(createForm, 'label','','','Email: ');
createElement(createForm, 'email', 'email', '','');
createSpanTag(createForm,'emailError');
createElement(createForm, 'button','Validate','Validate','');
document.getElementsByTagName('button')[0].addEventListener('click',validate());
document.getElementsByTagName('body')[0].appendChild(newDiv);
}
)();
function createElement(formElement,type,name,value, placeholder) {
if(type=='label'){
var element=document.createElement(type);
if(name!='' && value!=''){
element.setAttribute('name',name);
element.setAttribute('value',value);
}
element.innerHTML=placeholder;
formElement.appendChild(element);
} else {
var element=document.createElement('input');
if(type!=''){
element.setAttribute('type',type);
}
if(name!=''){
element.setAttribute('name',name);
}
if(value!=''){
element.setAttribute('value',value);
}
if(placeholder!=''){
element.setAttribute('placeholder',placeholder);
}
formElement.appendChild(element);
}
}
function breakTag(createForm){
createForm.appendChild(document.createElement('br'));
}
function validate(){
}
function createSpanTag(createForm, id){
var element=document.createElement('span');
element.setAttribute('id',id);
createForm.appendChild(element);
}
The second argument of addEventListener needs to be a function.
Change ...
document.getElementsByTagName('button')[0].addEventListener('click',validate())
to ...
document.getElementsByTagName('button')[0].addEventListener('click',validate);
Since your tag name is input, not button. So use input in parameter of the function getElementsByTagName() and then loop through all nodes and find node with type = button.
Try change this line:
document.getElementsByTagName('button')[0].addEventListener('click',validate());
to:
var nodeList = document.getElementsByTagName("input");
for (var i = 0; i < nodeList.length; i++)
{
if (nodeList[i].getAttribute("type") == "button") {
{
nodeList[i].addEventListener('click',validate);
}
}
I have a problem with my Script. I want to do the following steps in this order:
1. Save the text in the input field.
2. Delete all text in the input field.
3. Reload the same text that was deleted before in the input field.
The problem with my script is that the ug()- function writes undefined in my textbox instead of the string that should be stored in var exput. The alert(exput) however shows me the correct content.
Help would be very much appreciated. And I'm sure there is better ways to do that, I'm quite new to this stuff.
HTML
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();deleter();ug()" />
Javascript
function merker() {
var merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
Your code is calling merker(); deleter(); ug(); in the onclick event, but ug() is already called by merker(). You should be doing this instead:
function merker() {
var merkzeug = document.getElementById('a').value;
deleter();
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();" />
I changed Your Javascript:
function merker() {
merkzeug = document.getElementById('a').value;//global variable without var
ug();//why You use it here? I think only for test. So delete it after.
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug() {
alert(merkzeug);
document.getElementById('a').value =merkzeug;
};
Problems with your code:
method ug was used with argument and without argument ( i changed to without )
to restore deleted value it must be saved to some variable, i saved to global merkzeug variable - this is not good practice but sufficient in this case
next i used merkzeug to restore value in textarea in ug() function
i do not know why You using ug() two times? maybe delete one of them is good thing to do.
In plunker - https://plnkr.co/edit/fc6iJBL80KcNSpaBd0s9?p=info
problem is: you pass undefined variable in the last ug function:
you do: merker(value) -> ug(value); delete(); ug(/*nothing*/);
or you set your merkzeung variable global or it will never be re-inserted in your imput:
var merkzeug = null;
function merker() {
merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
if (typeof exput === 'undefined') exput = merkzeung;
alert(exput);
document.getElementById('a').value = exput;
};
Let's say you want to predefine a lot of buttons that are created by a button generator.
function createButton(name, func){
var btn = '<div class = "button" name = '+name+'/>';
$('.btn[name = "'+name+'"]').on('click', function(func){});
}
var butn1 = {
name : "exit",
func : func1
}
createButton(btn1);
Now if you had 100 buttons, this means a lot of variables. Is that bad? If it is, would this be better?
function chooseButton(name){
var btn;
switch(name){
case "exit":
btn = {
name : "exit",
func : func1
}
break;
case......
}
return btn;
}
var myBtn = chooseButton('exit');
createButton(myBtn);
If feel like it would be better to use a more general constructor for this sort of thing, assuming I've understood your question.
HTML
<div id="buttonContainer">
<button class="btn btn-type-a">Type A Button</button>
<button class="btn btn-type-b">Type B Button</button>
<!-- add further types -->
</div>
JS
var _functs = {
typeA: function () { alert('type A funct'); },
typeB: function () { alert('type B funct'); }
};
var _buttons = document.getElementById('buttonContainer')[0].childNodes;
for (var _i = 0; _i < _buttons.length; _i++) {
if (_buttons[_i].classList.contains('btn-type-a')) {
/*
node.classList.contains (not supported by IE < 10)
$(_buttons[_i]).hasClass('btn-type-a') if you're using jQuery
*/
_buttons[_i].addEventListener('click', _functs.typeA, false);
}
// other logic for other button assignment
};
I have the following code:
function mandatoryField(manF)
{
var fieldId = $(manF).val();
if(fieldId == "")
{
return false;
}
else
{
return true;
}
}
It doesn't work, but this does:
function mandatoryField()
{
var fieldId = $("#element_1").val();
if(fieldId == "")
{
return false;
}
else
{
return true;
}
}
Presume, on my first example, mandatoryField is called as such:
mandatoryField("#element_1")
Why doesn't it work when I try to replace the absolute element ID name with a variable?
Edit:
Most recent code - non-working:
function isAmExSelected()
{
return $("#creditCardType").val() == "American Express";
}
function containsOnlyDigits(str)
{
return str.match(/[^0-9]/) == null;
}
function validateCCNumber()
{
var ccn = $("#creditCardNumber").val();
var onlyDigits = containsOnlyDigits(ccn);
if(isAmExSelected())
{
return ccn.length == 15 && onlyDigits;
}
else
{
return ccn.length == 16 && onlyDigits;
}
}
function mandatoryField(manF)
{
var fieldId = $("#" + manF).val();
return fieldId != "";
}
function registerValidation(id, validateMethod(), errorMethod)
{
$(id).change(function(){
if(validateMethod() == false)
{
errorMethod();
}
});
}
$(document).ready(function(){
registerValidation("#creditCardNumber", validateCCNumber, function(){alert("Invalid Credit Card Number!")});
$('input[type=text][class=mandatory]').blur(function(){
if (mandatoryField(this.id)) {
alert('Field:' + this.id + ' is mandatory!')
}
});
});
Edit 2
I've rewritten the entire thing to look like this:
$('input[type=text][class=mandatory]').blur(function(){
if (!($("#" + this.id).val().length)) {
alert('Field:' + this.id + ' is mandatory!');
}
});
If a text input of the mandatory class blurs, then run the function: if #foo.val() does not have length (i.e. has no text in it), run the alert. I believe it should work, but it does not.
Update your code to so:
function mandatoryField(manF)
{
var fieldId = $("#" + manF).val();
if(fieldId == "")
{
return false;
}
else
{
return true;
}
}
and then try again.
Both pieces of code should work the same irrespective of whether the selector is passed in as an argument, or provided as a literal to $ directly. Also, instead of the if..else, you could do
function mandatoryField(manF) {
var fieldId = $(manF).val();
return fieldId != "";
}
Try this one:
function mandatoryField(manF)
{
if($('#' + manF).val() == "")
{
return false;
}
else
{
return true;
}
}
mandatoryField("element_1");
But this will get you value of element, not it's id. I'm not sure what you are tring to accomplish.
Trigger on field blur option:
$('input[type=text][class=classForMandatoryFields]').blur(function(){
if (mandatoryField(this.id)) {
alert('Field:' + this.id + ' is mandatory!')
}
});
Could you try:
var fieldId = manF.val();
mandatoryField($("element_1"));
Besides your selector problem, you could rewrite your function like this:
function mandatoryField(manF){
return $(manF).val().length;
}
This is, because in JavaScript everything has a truth or false meaning. For numbers, 0 is false.
EDIT:
My test works just fine:
function mandatoryField(manF){
return $(manF).val().length;
}
(...)
<input id="test" value=""/>
<input type="button" value="dd" onClick="alert('length: ' + (mandatoryField('#test'))"/>
Okay this will not work because jquery will assume manF is a DOM object but instead you are passing string.
have you ever tried
var tr = $('#element1') //----------1
alert($(tr).val()) //------------2
tr is actually a dom object
UPDATE::
why don't you try this one
//some code on some event
if(!check_mandatory())
//do something else
else do another thing
//some code on some event
and the function
function check_mandatory()
{
$('.mandatory').each(function{
if($(this).val() == ""){
alert($(this).attr("name") + "required");
//or you can use id or any attrib
return false;
}
})
}
note code might not work not tested, if it did not work then let me know