jQuery document ready functions not working - javascript

I'm working on a form with 5 divs and to keep the form as clean and tidy as possible, I kept 4 of them hidden with "display: none".
When the button (ex. Add Client) is clicked, I want the next div (up to 4 more) to be displayed with a js, and when the other button (ex. Remove Client) is clicked, I want the last displayed div to be hidden again.
JS:
<script>
$(document).ready(function addClient() {/*mycode*/});
$(document).ready(function removeClient() {/*mycode*/});
</script>
HTML:
<input id="kkBtnNewClient" type="button" value="New Client" class="kkButton" onclick="addClient()"/>
<input id="kkBtnRemoveClient" type="button" value="Remove Client" class="kkButton" onclick="removeClient()"/>
I tried to put a simple alert in the /mycode/ part, but I don't even get to that part.

The value you pass to ready() is called when the ready event fires.
It does not create a global variable from which to call the function.
Use a function declaration to do that. Better yet, bind the event handler with JavaScript and don't use onclick attributes at all.
$("#kkBtnNewClient").on("click", function addClient() {
alert("add client");
});
$("#kkBtnRemoveClient").on("click", function removeClient() {
alert("remove client");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="kkBtnNewClient" type="button" value="New Client" class="kkButton" />
<input id="kkBtnRemoveClient" type="button" value="Remove Client" class="kkButton" />

You may try like as below:
$(".group_1").hide();
$(".group_2").hide();
$(document).on('click','#kkBtnNewClient', function(){
console.log("kkBtnNewClient clicked");
$(".group_1").show();
$(".group_2").hide();
});
$(document).on('click','#kkBtnRemoveClient', function(){
$(".group_2").show();
$(".group_1").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="group_1">
div 1
</div>
<div class="group_1">
div 2
</div>
<div class="group_1">
div 3
</div>
<div class="group_1">
div 4
</div>
<div class="group_2">
div 5
</div>
<input id="kkBtnNewClient" type="button" value="New Client" class="kkButton" />
<input id="kkBtnRemoveClient" type="button" value="Remove Client" class="kkButton" />

Related

Create HTML text in an HTML form and open up the text in a Javascript alert box

I'm new to coding and need to create HTML text in an HTML form on a page and open up the text in a Javascript alert box. I've tried various code to no success. Here is what I've come up with so far which does not create a pop up alert box:
Here is the HTML and the JS:
Function myfunction1()
{
Let myfun1 = document.getElementById('sec1-input').value;
Alert(myfun1);
}
<div class="form-group">
<label for="sec1-input"><strong>Enter Alert Text: </strong></label>
<input type="text" class="form-control" id="sec1-input">
</div>
<button id="sec1-btn1" type="button" class="btn btn-primary">Alert Me!</button>
I'm not sure what do you want, but I'll show you how to make an alert window exactly as you're asking.
First of all you must consider several mistakes that you are making. JavaScript does not recognize the word Function because it is capitalized. The function keyword must be lowercase.
Here I leave you a referring link with JavaScript reserved words: https://www.w3schools.com/js/js_reserved.asp
On the other hand, I see that you are not using the form tag, which leads to two problems: technical and semantic. Here I leave you another link with reference to forms: https://www.w3schools.com/html/html_forms.asp
Finally, to achieve what you want you need to work with events, especially with the click event. Here I will leave you a reference link and the solution you want:
let button = document.querySelector('#sec1-btn1');
button.addEventListener('click', function(e) {
let val = document.querySelector('#sec1-input').value;
alert(val);
});
<form>
<div class="form-group">
<label for="sec1-input"><strong>Enter Alert Text: </strong></label>
<input type="text" class="form-control" id="sec1-input" />
</div>
<button id="sec1-btn1" type="button" class="btn btn-primary">
Alert Me!
</button>
</form>
You have not called the function anywhere. For it to work you need to use a listener.
<div class="form-group">
<label for="sec1-input"><strong>Enter Alert Text: </strong></label>
<input type="text" class="form-control" id="sec1-input">
</div>
<button onclick="myfunction1()" id="sec1-btn1" type="button" class="btn btn-primary">Alert Me!</button>
<script>
function myfunction1() {
let myfun1 = document.getElementById('sec1-input').value;
alert(myfun1)
}
</script>
I added the onClick listener to button and now it works.
javaScript is case sensitive
function myfunction1()
{
let myfun1 = document.getElementById('sec1-input').value;
alert(myfun1);
}
<div class="form-group">
<label for="sec1-label"><strong>Enter Alert Text: </strong></label>
<input type="text" class="form-control" id="sec1-input">
</div>
<button id="sec1-btn1" type="button" onClick="myfunction1()" class="btn btn-primary">Alert Me!</button>
also IDs of elements should not be the same , to assign same selector , use class and you also need to give your function to your element's event listener
You should not start javascript functions like alert with capital letters.
Put this piece of code instead of your button:
<button id="sec1-btn1" type="button" class="btn btn-primary" onclick="myfunction1()">Alert Me!</button>

Javascript function only works on the first call

I'm developing a Question&Answer website in php and I want to print the answer comments when I press the button. Everything works like a charm but only on the first button. I have an idea why this does't work, I guess it only takes into account the first id that it finds.
So , my question is, is there any way to name the element I want to call based on its id? For example:
<button class="btn icon-chat" title="Add a comment on this answer"
type="button" id="showarea . {answer['answerid']"} name="showarea" value="Show Textarea">
Comment</button>
<div id="textarea">
{include file="comment_form.tpl"}
</div>
But how would I call this PHP variable on my JS function?
$("#textarea, #textarea-ok").hide(); // or you can have hidden w/ CSS
$("#showarea").click(function(){
$("#textarea").show();
});
$("#textarea-ok, #cancel").click(function(){
$("#textarea").hide();
});
Is this the best approach? Any advise regarding to the JS code you can give?
Kind Regards
Live method should be ok
$("body").on("click", ".myClass", function(){
// do it again // or #myId
});
Don't forget about an event with an Id selector can be only on one element, and class on every one...
Edit with example
<div class="post-button clearfix">
// i changed this button as well
<button class="btn icon-chat show-textarea" title="Add a comment on this answer" type="button" data-answer="{$answer['publicationid']}">Comment</button>
<div class="textarea">
{include file="comment_form.tpl"}
</div>
</div>
// comment_form.tpl
// i added a master container
<div class="comment-form">
<form method="post" action="{$BASE_URL}controller/actions/comments/create_comment.php">
<textarea name="comment" rows="4" cols="40" class="qa-form-tall-text"></textarea>
// i deleted the wrong input here
<input type="hidden" name="answerid" value="{$answer['answerid']}" />
<input type="hidden" name="questionid" value="{$question['publicationid']}" />
// i changed these 2 buttons as well
<button type="button" class="textarea-cancel qa-form-tall-button qa-form-tall-button-comment">Cancel</button>
<button type="submit" class="textarea-ok">Ok</button>
</form>
</div>
Then you change the script with class in selector like :
...
$('.comment-form').hide();
$("body").on("click", ".show-textarea", function(){
$('.comment-form').show();
});
$("body").on("click", ".textarea-ok, .textarea-cancel", function(){
$('.comment-form').hide();
});
....
More about Jquery Selector : https://www.w3schools.com/jquery/jquery_ref_selectors.asp
More about live method wit .on() :
https://www.w3schools.com/jquery/event_on.asp
More about Html forms
https://www.w3schools.com/html/html_forms.asp
Read these docs to be ok with yourself ;)

pass values from separate divs into a javascript function

I have a form that has three separate divs within it.
<form method="post">
<div id = "f1">
<div class="label">Value 1:</div>
<input type="text" name="name"/>
<button id = "next1" type="button" onclick="checkValue()">Next</button>
</div>
<div id ="f2">
<div class="label">Value 2:</div><br>
<input type="text" name="name"/>
<button type="button" onclick="checkValue()">Next</button><br>
</div>
<div id ="f3">
<div class="label">Value 3:</div><br>
<input type="text" name="name"/>
<button type="button" onclick="checkValue()">Next</button><br>
</div>
</div>
</form>
In my javascript function. I have a fadein and fadeout attached to each div when the next button is pressed. When the "next1" button is pressed the first div will be faded out and the second div will fade in. I want to check the values inputted in the first div when the user presses the first next button. I know how to do this if i just passed in the whole form into my javascript function on the final submit button, but I would like to know how to do this after each next button is pressed.
I also will have more than one value in each of the divs (f1, f2, f3) but for simplicity I only included one value.
EDIT*: further explaintaion
If i did this by passing in the form into checkValue. I could just do an onsubmit = "checkValue()". And then in my JS file, I would just include checkValue(form) as its parameter. If i want to do a check after every single button is pressed, I am not sure how to do this or what to pass in as its parameter.
Simple mock up hopefully to get you one your way.
Fiddle: http://jsfiddle.net/AtheistP3ace/krr3tgLx/1/
HTML:
<form method="post">
<div id="f1" style="display: block;">
<div class="label">Value 1:</div>
<input type="text" name="name" />
<button id="next1" type="button" onclick="checkValue(this)">Next</button>
</div>
<div id="f2">
<div class="label">Value 2:</div>
<br>
<input type="text" name="name" />
<button type="button" onclick="checkValue(this)">Next</button>
<br>
</div>
<div id="f3">
<div class="label">Value 3:</div>
<br>
<input type="text" name="name" />
<button type="button" onclick="checkValue(this)">Next</button>
<br>
</div>
</div>
</form>
JS:
function checkValue (button) {
// Finds the sibling input of the button
var input = $(button).siblings('input');
// Gets input value
var value = input.val();
// Stops showing next div if no value
if (value == '') {
return false;
}
else {
// Finds the parent div holding button and input
var div = $(button).closest('div');
// Fades out current div
div.fadeOut();
// Gets next div and fades it in
div.next().fadeIn();
}
}
CSS:
form > div {
display: none;
}
From my assumptions this is what you are looking for :
Multipart form handler
Basically I wired up each button with a class
<button id = "next1" type="button" class="check-btn">Next</button>
Then I used Jquery to get all those buttons and find the parent div (based on your structure) and then get all the child inputs (can include selects etc). From here you can continue to tweak to perform a check on each type of input etc.
$(document).ready(function(){
$('.check-btn').on('click',function(){
var parent = $(this).parent('div');
var elems = parent.find('input');
alert(elems.length);
//DO checks here for each element
});
});

replaced Button wont work

i have this html form
<form action="" method="post" name="login_form">
Email : <input type="text" id="email2" name="email" /><br />
<span id="passwordT" >Password : </span>
<input type="password" name="password" id="password2"/><br />
<input type="button" id="submit_botton" value="Login" />
<div><input id="forgot" type="button" value="Forgot your Password?" /></div>
</form>
and the javascript here
var forgot = $('#forgot');
var forgot2 = $('#forgot2');
forgot.click(function() {
$('#password2').hide();
$('span#passwordT').hide();
$('input#submit_botton').prop('value', 'Reset Passowrd');
$('input#forgot').replaceWith('<input id="forgot2" type="button" value="Login here" />');
});
$('input#forgot2').click(function() { // this function didnt want to work
$('input#forgot2').prop('value', 'Forgot your Password?');
$('#password2').show();
$('span#passwordT').show();
$('input#submit_botton').prop('value', 'Login');
});
HERE JS-DEMO
what i want is :
when i click on second function i will get back the buttons as they were in first time.
I tried to make this second function inside the first but what i got is the function works but only one time , i mean if i click again to reset password will not work.
thanks for the help.
Your problem is that you're trying to attach an event handler to an element that doesn't exist yet. That's not possible with direct event handlers. Use delegated events instead.
$(document).on('click','#forgot2', function(){ ... });
document can be replaced with any #forgot2 container that exists at binding time.
As a side note, take into account that when you use selectors by id (e.g #forgot2) it's not necessary to add anything else since an id identify one and just one element (repeated ids are not allowed). So this selector input#forgot2 is not wrong but more complex than necessary.

Execute javascript function in chain of button clicks

On my original post I wasn't for sure on the amount of depth I should go to. Here is what I have been working on since the jQuery answer was posted:
I am attempting to execute a task which requires the user to choose and click one html button out of a series of buttons and then be required to choose another html button out of a series of buttons.
Essentially I would like the value of the first button selection to be passed as a parameter to a function that will run when the user clicks the second button. I'm just learning javascript and I'm lost.
Thank you
HTML:
<form id="scoreboard">
<div>
<input type="text" name="homeTeam" value="00" size="2" "readonly" id="homeTeamScore"/>
<input type="button" value="+1" name="add1" id="homeAdd1" class="homeScore" onClick="calcScore(1)"/>
<input type="button" value="-1" name="neg1" id="homeNeg1" class="homeScore" onClick="calcScore(4)"/>
</div>
<div>
<input type="button" name="homeP1" id="homeP1" class="player" value="24" style="text-align:center;"/>
<input type="text" name="homeP1Score" value="0" size="2" style="text-align:center;"/>
</div>
<div>
<input type="button" name="homeP2" id="homeP2" class="player" value="44" style="text-align:center;"/>
<input type="text" name="homeP2Score" value="0" size="2" style="text-align:center;"/>
</div>
</form>
Javascript:
function calcScore(amount) {
if(amount==1) {scoreboard.homeP1Score.value++;scoreboard.homeTeam.value++;}
else if(amount==4) {scoreboard.homeP1Score.value--;scoreboard.homeTeam.value--;}
}
$('.player').click(function() {
//initialize the second button listener
var data = $(this).attr('data');
$('.homeScore').click(function() {
function addHomeScore(data)
});
});
Using jQuery:
$('#buttonId').click(function() {
//initialize the second button listener
var data = $(this).attr('data');
$('#button2Id').click(function() {
yourFunction(data);
});
});
This method is better because it uses JavaScript scoping to avoid globals. Since JavaScript (especially with jQuery) sometimes has multiple threads/functions executing at the same time, it's very easy to run into problems with globals. They're also very hard to test and unsafe.
In raw JavaScript:
HTML:
<button class="button1" onclick="saveValue()" />
<button class="button2" onclick="callMethod()" />
JavaScript:
myGlobalVariable = null;
function saveValue(){
myGlobalVariable = "Value That Was Selected";
}
function callMethod(){
alert(myGlobalVariable + "I HAZ ACCESS TO GLOBALS!!!!");
}
In jQuery:
HTML:
<button class="button1" />
<button class="button2" />
JavaScript:
myGlobalVariable = null;
$('button.button1').click(function(){
myGlobalVariable = "Value That Was Selected";
});
$('button.button2').click(function(){
alert(myGlobalVariable + "I HAZ ACCESS TO GLOBALS!!!!");
});
setup some global variable in js. then on each button setup some onClick events that go and change the global var. then the next button click can check to see the value in the global var
<button onclick="myFunction()">Click me</button>

Categories