Toggle button by passing jquery variable - javascript

I have in my html:
<input type="button" value="Start L/D" id="start_ld" name="start_ld" onclick='return(toggle_server_create("start_ld", "stop_ld", false));' />
<input type="button" value="Stop L/D" id="stop_ld" name="stop_fx_ld" style="display:none;" onclick='return(toggle_server_create("start_ld", "stop_ld", true));' />
In my javascript/jquery:
function toggle_server_create (start_id, stop_id, state){
var query = '#' + start_id +',' + '#' + stop_id;
var query_stop = '#' + stop_id
var query_start = '#' + start_id
// console.log(state);
// console.log(query_stop);
$(query).click(function() {
// console.log(query_start);
// console.log (this.name);
if ((this.name === start_id) && $(this).is(":visible") && state==false) {
console.log("Show stop")
$(query_stop).show();
}
else if ((this.name === stop_id) && $(this).is(":visible") && state == true) {
console.log("Show start")
$(query_start).show();
}
$(this).hide();
});
}
The toggle_server_create should accept the jQuery variables and toggle between start and stop accordingly. However, it doesn't function that way but instead has to be clicked twice to see the button changed and when clicked again it disappears. I'm new to JavaScript and I'm not sure how to fix this.

Your issue is a result of setting a click handler only after the user clicks the button. When your button is clicked toggle_server_create is run. When it runs, it creates a click handler for the two buttons that says, "when you click this button, execute everything in this function.
So, the first time you do this only your query variables are set, and then a click handler is created that will execute whenever one of those buttons is set. That is why the second time you click it works.
The code is a bit confusing so I'm not 100% sure what you are trying to accomplish, but that is what is causing it to only run on the second click.
If you are truly trying to just toggle between the buttons, consider something like this: https://jsfiddle.net/bb14xn7z/1/
Where your html is:
<input type="button" value="Start L/D" id="start_ld" name="start_ld"/>
<input type="button" value="Stop L/D" id="stop_ld" name="stop_fx_ld" style="display:none;"/>
And your javascript is:
$(function() {
$("#start_ld").click(function() {
$(this).hide();
$("#stop_ld").show();
});
$("#stop_ld").click(function() {
$(this).hide();
$("#start_ld").show();
});
});
Notice how I do not set onclick in the html, and instead set up the click handler in javascript on page load.

there are two problems here, HTML doesn't use apostrophe for attribute values
<input type="button" value="Start L/D" id="start_ld" name="start_ld" onclick="return toggle_server_create('start_ld', 'stop_ld', false));" />
and you don't have to pass those IDs since they're static, you could store them in a variable in the JavaScript or hardcode them into the function to give more flexibility

You can do it with jquery simple as this :)
https://jsfiddle.net/p1tmaoh7/
html
<div class="buttons">
<input type="button" value="Start L/D">
<input type="button" value="Stop L/D" style="display:none;">
</div>
jquery
$(document).ready(function(){
$('.buttons input').click(function(){
$('.buttons input').toggle();
});
});

Related

Select all checkbox only works some of the time

I have a form with checkboxes, along with a hidden select all button inside the form. I use jQuery to listen for a button click outside the form, and then "click" the hidden button element to select all. Sometimes the page loads up and I click the button and it works perfectly. You can click it multiple times and they all check and uncheck as intended. The form submits perfectly.
Other times, however, the page will load up and I click the button and nothing happens. They don't check no matter how many times I click. I've found this happens a lot if the page sits for more than maybe 10 seconds without me doing anything. But it also can happen on page load. I can't understand why. Is there an error in my code somewhere that I'm just not seeing?
$(document).ready(function(){
$('#select-all').click(function(event) {
if(this.checked) {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = true;
$('label.choice').toggleClass("choice-text-color");
});
} else {
$(':checkbox').each(function() {
this.checked = false;
$('label.choice').toggleClass("choice-text-color");
});
}
});
$("#selectAll").click(function() {
$('#select-all').click()
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="selectAll" class="btn btn-secondary my-2 my-sm-0"
type="button" name="selectAll">Select All</button>
<form>
<input type="checkbox" id="1"><label for="1" class="choice">ABC</label>
<input type="checkbox" id="2"><label for="2" class="choice">DEF</label>
(....etc.....)
<input type="checkbox" id="select-all" style="display: none;">
<input type="submit" style="display: none;">
</form>
It seems to me that your issue is due to the extraneous markup you've added to facilitate the select all functionality and the JavaScript/JQuery tied to it.
All you need is a single button (it doesn't matter whether it's part of the form or not) to trigger the select/deselect operations. Also, since the button will not be transmitting any data as part of the form the name attribute should not be used.
Also, if you don't want users to see the form's submit button, then simply don't add one to the form. You can then programmatically submit the form with $(form).submit().
// Passing a function into JQuery is the same as document.ready
$(function(){
// JQuery recommends the use of "on" to bind events
$('#selectAll').on("click", function(event) {
$(':checkbox').each(function() {
this.checked = true;
});
$('label.choice').addClass("choice-text-color"); // Update the class use
});
});
.choice-text-color {
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="selectAll" class="btn btn-secondary my-2 my-sm-0" type="button">Select All</button>
<form>
<input type="checkbox" id="1"><label for="1" class="choice">ABC</label>
<input type="checkbox" id="2"><label for="2" class="choice">DEF</label>
</form>

How to add many html buttons that use same javascript into loop results?

I have the following codes on my html page:
<input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="metin" placeholder="Geben Sie Artikel Nr" style="width: 30%;"/><br/><br/>
<input type="button" class="single_add_to_cart_button button alt" value="Suche (Advanced)" onclick="search()" /><br/><br/>
<div class="cevap" style="background-color:#e6e6e6; border: 0px solid green; padding: 2px; margin: 0px;"><i class="fa fa-spinner fa-spin fa-2x"></i></div>
and between <head> ... </head> :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function search() {
metin = $('input[name="metin"]').val();
$.post('/wp-content/plugins/ajax-test/SearchByNumberNew.php', {yazi: metin}, function (gelen_cevap) {
$('.cevap').html(gelen_cevap);
});
}
</script>
I am sending yazi into SearchByNumberNew.php and after some processes inside it I am getting the results into <div class="cevap"...
Until here it is okay. I am trying to put several buttons next to every result in the <div> that are sending the related value ($parcano)again into SearchByNumberNew.php. So I want to make a new search with the new value and refill the <div> with the new results (of course after deleting the previous results).
to do that I added following code into the loop in the SearchByNumberNew.php:
...
?><input type="hidden" name="metin" value="<?php echo $parcano;?>"/><br/><br/>
<input type="button" class="single_add_to_cart_button button alt" value="Suche (Basic)" onclick="searchin()" /><br/><br/>
<?php
...
and following code between <head> ... </head> :
function searchin() {
metin = $('input[name="metin"]').val();
$.post('/wp-content/plugins/ajax-test/SearchByNumberNew.php', {yazi2: metin}, function (gelen_cevap) {
$('.cevap').html(gelen_cevap);
});
}
I tried many variations: yazi, yazi2, metin, metin2, etc..., unsetting the values before the loop, etc...
In the first search that I enter the value in the input box, it is always okay. I get a list of results with many buttons for each result line.
As far as I see in the button codes on the page, all of them have the correct values.
But when I click any of them, they always send the first buttons value into my php file.
What am I doing wrong?
I would appreciate for your kind helps,
Regards,
Murat
Have you tried to start your jQuery block?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
(function($) {
function search() {
var metin = $('input[name="metin"]').val();
$.post('/wp-content/plugins/ajax-test/SearchByNumberNew.php', {yazi: metin}, function (gelen_cevap) {
$('.cevap').html(gelen_cevap);
});
}
})( jQuery );
</script>
As far I see your code, no where I see you are using the value of button. Instead you are using value of a input box. If you use the value $('input[name="metin"]').val() then jquery will search for input box from top of the page and return you the first result it matches. So it will always bring the first result.
There are couple of ways to do solve your problem. You can pass this parameter in the button onClick event and as a button value you can give reference to the input you want to take the value from
<input type="button" class="single_add_to_cart_button button alt" value="metin1" onclick="searchin(this)" />
function searchin(param) {
metin = $('input[name="+ param.val() + "]').val();
$.post('/wp-content/plugins/ajax-test/SearchByNumberNew.php', {yazi2: metin}, function (gelen_cevap) {
$('.cevap').html(gelen_cevap);
});
}
Or second way is bind a jquery event to a button.
$('.single_add_to_cart_button').click(function(){
metin = $('input[name="+ this.val() + "]').val();
})
As far I understood your question. I think this way you can achieve your task. Otherwise let me know if have any queries.
The problem is that you're using the wrong identifier $('input[name="metin"]').val(); will always return the value of the last input with name metin, try grouping each input group in a div and instead of:
$('input[name="metin"]').val();
use this if you want to use the input's value
$(this).parent().find('input[name="metin"]').val();
and this if you want to use the button's value
$(this).val();
The php code should look something like this:
...
?>
<div>
<input type="button" class="single_add_to_cart_button button alt" value="Suche (Basic)" onclick="searchin()" /><br/><br/>
</div>
<?php
...

Show element in JavaScript by onkeypress function

I'm trying to show save button only if input gets value,
The issue is if i use append for each input i get 1 button printed, what I'm looking for is regardless of input length get the button only once.
The important is input not be empty that's all.
Code
<input class="text_dec form-control" type="text" onkeypress="myFunction()" name="text_dec[]" id="'+ textFieldsCount.toString() +'">
function myFunction() {
$('#moreless').append("button here");
}
any idea?
Instead of keypress, use keyup, this will call the listener just when the key is released, so you will have the correct length of the input value. With that, you can check if the button must be displayed or not.
Also, I would have another check to make sure that input have some value on it to save when clicked.
Like below, take a look:
$(function(){
$('.myInput').on('keyup', function(){
var btnElem = $('.myButton');
var charLength = this.value.length;
if (charLength > 0){
btnElem.show();
}else {
btnElem.hide();
}
});
$(".myButton").on("click", function(){
if ($('.myInput').val().trim().length < 1){
alert("Input is empty")
return;
}
//Do your code
});
});
.myButton {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="myInput" type="text" value="">
<input class="myButton" type="button" value="Save Button" />
</body>
EDIT
Now, if you really need to make as you were doing before (I don't consider it a best practice and also recommend you to rethink if you really wanna go through this) here goes a code that will help you. Click to show.
Here I added the functions and created the button element (if necessary) then append it to DOM just when the input have some value length.
function myFunction(input){
var btnElem = $(".mySaveButton")[0];
if (!btnElem){
btnElem = document.createElement("button");
btnElem.textContent = "Save Button";
btnElem.onclick = btnClicked;
btnElem.className = "mySaveButton";
}
var charLength = input.value.length;
if (charLength > 0){
document.body.append(btnElem);
}else {
btnElem.remove();
}
};
function btnClicked(){
if ($('.myInput').val().trim().length < 1){
alert("Input is empty")
return;
}
//Do your code
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="myInput" type="text" value="" onkeyup="myFunction(this)">
</body>
So I think you just want a button to show to the user once they type something in the text box. If that's the case, then you don't really want to append a button every time they press a key in the box.
Instead I'd make a button and set its css to display none and then when they keydown in the text box change the button's css to display block.
Something like this: http://jsfiddle.net/wug1bmse/10/
<body>
<input type="text">
<input class="myButton" type="button" value="button text" />
</body>
.myButton {
display: none;
}
$(function(){
$('input').on('keypress',function(){
var htmlElement= $('.myButton');
htmlElement.css('display', 'block');
});
});
Hiding the element with a class might be easier:
.btn-hidden {
display: none;
}
<input id="save-button" class="btn-hidden" type="button" value="save" />
function showSave() {
$('#save-button').removeClass('btn-hidden');
}
function hideSave() {
$('#save-button').addClass('btn-hidden');
}

Multiple "link" submit buttons in one form

I would like to create a form with multiple submit link buttons. I know it can be done by using and specifying the name of <button> or <input type="button"> something like this:
In HTML:
<form action="" method="get">
Other form elements here...
<button type="submit" name="activated">Activated</button>
<button type="submit" name="pending">Pending</button>
<button type="submit" name="suspended">Suspended</button>
</form>
In PHP:
<?php
if(isset($_GET["activated"])) {
Activated codes here...
}
elseif(isset($_GET["pending"])) {
Pending codes here...
}
elseif(isset($_GET["suspended"])) {
Suspended codes here...
}
?>
I want the submit buttons to be done by using link, not <button> or <input type="submit"> something like this:
Activated
Pending
Suspended
I heard that it can be done by using JavaScript or JQuery but I don't know how, anyone knows?
Update: What I want to happen is when I clicked the "Activated" link for example, I want only to process the logic under isset($_GET["activated"]).
The reason behind:
The reason why I want to have a submit link buttons instead of normal submit button tags is that, I want to use this bootstrap dropdown button style to change the status of user(s) on table:
and it is based on links, so that's why.
PS: Sorry for bad English, not my native language.
You could use data attributes on your anchors, then load that attribute into a hidden field to check in your PHP code.
<form action="" method="post">
Activated
Pending
Suspended
<input type="hidden" id="actionName" name="actionName" value="" />
</form>
$('.anchor-btn').click(function(e) {
e.preventDefault();
$('#actionName').val($(this).data('name'));
$('form').submit();
});
<?php
if($_POST['actionName'] == "activated") {
Activated code goes here
}
...etc.
?>
Yes you can submit the form using jquery just add a class to your buttons and add a click handler
$(document).ready(function() {
$( ".buttons_class" ).click(function() {
$( "#target_form" ).submit();
});
});
so your buttons will look like this
<button type="button" name="activated" class="buttons_class">Activated</button>
<button type="button" name="pending" class="buttons_class">Pending</button>
<button type="button" name="suspended" class="buttons_class">Suspended</button>
if using anchors
Activated
Pending
Suspended
And in javascript
$(document).ready(function() {
$( ".buttons_class" ).click(function(e) {
e.preventDefault(); //This will stop the default anchor action
$("#target_form").attr("action", "yourphpfile.php?"+$(this).text()+"=true"); //This will send the text inside the anchor as a GET param.
$( "#target_form" ).submit();
});
});
However if I were you I would consider using POST instead of GET for this. and do something like this
$( ".buttons_class" ).click(function(e) {
e.preventDefault(); //This will stop the default anchor action
var paramName = $(this).text(); //get text inside anchor
$( "#target_form" ).submit(function(eventObj) {
$('<input />').attr('type', 'hidden')
.attr('name', paramName);
.attr('value', "something")
.appendTo('#form');
return true;
}); //Add hidden field
});
Change your isset to $_POST instead of $_GET, it will then use the name attributes.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['test1'])) {
###
} else if ($_POST['test2']) {
###
}
}
<form method="post">
<input name="test1" type="submit" value="TEST 1" />
<input name="test2" type="submit" value="TEST 2" />
</form>

Javascript Logic Problem

I know only what I need but I do not know how to get that done.
This is the logic of the code, I really hope some of you has the solution.
How can I create in javascript or jQuery a function that will do the following?
If that checkbox is selected, when the button is clicked redirect the user to another page by passing the value of the textarea in the URL.
So that is the logic.
We have three elements.
1)The checkbox
2)The input type button
3) The textarea.
The checkbox is selected, the user clicks on the button and the user goes to another page , and the URL will include the value found in the textarea.
i.e.
http://mydomainname/page.php?ValueThatWasinTextArea=Hello World
Can you help me.
I think it is something simple for a javascript coder.
Thank you so much
$(function(){
$(':button').click(function(){
if($('input[type="checkbox"]').is(":checked")){
window.location.href = "http://mydomainname/page.php?ValueThatWasinTextArea="+ $('textarea').val();
}
});
});
**Of course if there's more than these three elements on the page, you're going to want some more specific selectors
You could subscribe to the submit event of the form and inside test if the checkbox was checked and if yes use window.location.href to redirect to the desired url:
$('#id_of_the_form').submit(function() {
var value = encodeURIComponent($('#id_of_textarea').val());
if ($('#id_of_checkbox').is(':checked')) {
window.location.href = '/page.php?ValueThatWasinTextArea=' + value;
return false;
}
});
If the button is not a submit button you can subscribe for the click event of this button and perform the same logic.
Might be some syntax problem because I code this on top of my head
<input id="myCheckbox" type="checkbox" />
<button id="myButton" onClick="buttonClick" />
<input id="myTextArea" type="textarea" />
<script>
function buttonClick()
{
var checkBox = document.getElementById('myCheckbox');
var textArea = document.getElementById('myTextArea');
if(checkBox.checked)
{
window.location = 'http://mydomainname/page.php?ValueThatWasinTextArea=' + textArea.value;
}
}
</script>
$(document).ready(function() {
$('#btnSubmit').click(function() {
if($('#chkBox').is(':checked')) {
window.location = '/page.php?passedValue=' + $('#txtField').val();
}
});
};
...
<form>
<p>
<input type="checkbox" id="chkBox"> Checkbox</input>
</p>
<p>
<input type="text" id="txtField" value="" />
</p>
<p>
<input type="submit" id="btnSubmit" value="Submit" />
</p>
</form>

Categories

Resources