Jquery .click() not working multiple button - javascript

I want show alertbox on click button but more of button the some ID attr and work click on first button but not working click on second button.
Jquery;
jQuery("#submit").click(function(e){
alert("message");
});
HTML; (Repeat html per message)
<div class="reply">
<form id="vivam" method="post" onsubmit="return false;">
<textarea name="reply" placeholder="Write reply here"></textarea>
<p class="stdformbutton">
<button id="submit" class="btn btn-primary">Reply</button>
</p>
</form>
</div>
jsfiddle Link
What is the solution to this problem? Thank you in advance for answers.

Approach 1: IDs should be unique, use class instead of id.
HTML:
<div class="reply">
<form id="vivam" method="post" onsubmit="return false;">
<textarea name="reply" placeholder="Write reply here"></textarea>
<p class="stdformbutton">
<button class="btn btn-primary submit">Reply</button>
</p>
</form>
</div>
JS:
jQuery(".submit").click(function(e){
alert("message");
});
Working Demo Approach 1
Approach 2: You can also use attribute value selector to target element with same id. However this breaks the rule ids should be unique.and i do not recommend you using this:
jQuery("[id=submit]").on('click',function(e){
e.preventDefault();
alert("test");
});
Working Demo Approach 2

ID Must be unique .
Handler get attached to the first element with the id only.
Use class instead of id .
Fiddle Demo
Change HTML
<button class="btn btn-primary submit">Reply</button>
// ^ add class submit and remove id submit

Make it
jQuery(".submitbuttons").click(function(e){
and then
<button id="submit" class="btn btn-primary submitbuttons">Reply</button>
and please give unique ids and I recommend to set the button-type attribute (button or submit)

You can use the on listener in JQuery. That way you listen on an class, and then do something with the id...
Here's an JSFiddle of the working code...
The HTML ( note that i've changed the ID's because ID's need to be unique, and add the class to the buttons ):
<div class="reply">
<form id="vivam_1" method="post" onsubmit="return false;">
<textarea name="reply" placeholder="Write reply here"></textarea>
<p class="stdformbutton">
<button id="button_1" class="btn btn-primary submit">Reply</button>
</p>
</form>
</div>
<div class="reply">
<form id="vivam_2" method="post" onsubmit="return false;">
<textarea name="reply" placeholder="Write reply here"></textarea>
<p class="stdformbutton">
<button id="button_2" class="btn btn-primary submit">Reply</button>
</p>
</form>
</div>
And the JQuery part:
$('body').on('click', '.submit', function () {
e.preventDefault();
alert("Clicked on button " + $(this).attr('id'));
});

Related

Disable or enable only the current button

With a PHP for each cycle, I'm bringing articles from the database. In those articles, we have a comment section with a form. I want to check with jQuery if there is something written on the input before the comment is sent.
As the articles are being brought with a PHP cycle, I want to check only the article in which it is being written a comment, but jQuery checks all the articles and only enables or disables the first or top result being brought from the database. I want jQuery to check only on the article with a written comment.
Here's what I'm doing:
$(document).ready(function() {
$(".comment-submit").attr("disabled", true);
$("#group-post-comment-input").keyup(function() {
if ($(this).val().length != 0) {
$(".comment-submit").attr("disabled", false);
} else {
$(".comment-submit").attr("disabled", true);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" id="group-post-comment-input">
<button class="comment-submit">
Comment
</button>
</form>
<br>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" id="group-post-comment-input">
<button class="comment-submit">
Comment
</button>
</form>
<br>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" id="group-post-comment-input">
<button class="comment-submit">
Comment
</button>
</form>
As you can see on the snippet above, the buttons only get enabled when text is written on the first input only. I want the buttons to get enabled when text is written on their dependent input. If input 2 has text on it, enable button 2, and so on and so on.
How can I do that?
Since IDs must be unique to the DOM tree, you might consider using a class instead.
$(function() {
$(".group-post-comment-input").on('keyup', function() {
let $button = $(this).next('.comment-submit');
let disabled = !this.value;
$button.prop('disabled', disabled);
});
});
form {
margin: 0 0 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" class="group-post-comment-input">
<button class="comment-submit" disabled>Comment</button>
</form>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" class="group-post-comment-input">
<button class="comment-submit" disabled>Comment</button>
</form>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" class="group-post-comment-input">
<button class="comment-submit" disabled>Comment</button>
</form>
In my demonstration, I use jQuery's next() to traverse from the input on which the "keyup" event is fired to its associated button.
.next( [selector ] )
Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
Another method is to traverse up to the form element with closest() and back down to the button with find(). This might be useful if you expect your HTML structure to change in a way that could break the next() traversal.
let $button = $(this).closest('form').find('.comment-submit');
I also recommend using prop() instead of attr() to enable and disable inputs.
ID must be unique,
but you need to use a name for sending information to your PHP server
document.querySelectorAll('button.comment-submit').forEach( bt => bt.disabled = true )
document.querySelectorAll('input[name="group-post-comment-input"]').forEach( inEl =>
inEl.oninput = e =>inEl.nextElementSibling.disabled = (inEl.value.trim().length === 0) )
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" name="group-post-comment-input">
<button class="comment-submit"> Comment </button>
</form>
<br>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" name="group-post-comment-input">
<button class="comment-submit"> Comment </button>
</form>
<br>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" name="group-post-comment-input">
<button class="comment-submit"> Comment </button>
</form>

jquery prevent box to close after submit a form

After setting up a simple box dialog form I would like to keep the box open after submitting the form, but the box keeps closing.
After a little search into the jquery docs I came with preventDefault method on the event. I added that to the code, but the box keeping closing.
Here is the code:
$(document).ready(function(e) {
$('#toggle').click(function(e) {
$('#box').toggleClass('max');
e.preventDefault();
});
$('#close').click(function(e) {
/* $('#box').remove();*/
});
});
It did not work, I've tried the stopPropagation() and that did not worked either.
someone can spare a hint, please?
the html:
<div id="box" class="min">
<span id ="toggle" class="fa fa-window-restore">
<b>Open Dialog</b>
</span>
<form action="/conversations/3/reply" accept-charset="UTF-8" method="post">
<input name="utf8" type="hidden" value="✓" />
<input type="hidden" name="authenticity_token" value="VgKXI1p4MumSlvZF51pbXYKMMRLFKs0Us4NUB2+O7VZalzk++QDNQ5SsQMzvt4HlgUnlMa3ux54IDc3R/tGZhA==" />
<textarea name="body" id="body" cols="3" class="form-control" placeholder="Type something..." required="required"></textarea>
<button name="button" type="submit" class="btn_green">Send Message</button>
</form>
</div>
You need to call preventDefault() on the form's submit event in order to prevent the page from being replaced by the form submission.
document.querySelector('form').addEventListener('submit', e => e.preventDefault());

get value of form with submit without refreshing the page

I will explain my problem: I have a form and I want to click on submit to display a div (in the same page) and run a java script function without refreshing the page
<form action="#" method="post" name= "form1" id = "form1">
<div class="row_ligne">
<div class="col-25">
<label for="fname">Fréquence </label>
</div>
<div class="col-75">
<select id="frequence" name="frequence" onchange="showDiv(this)">
<option value="yearly">Annuelle</option>
<option value="monthly">Mensuelle</option>
<option value="daily">Quotidienne</option>
</select>
</div>
</div>
<div class="row_ligne">
<div class="col-50">
<input type="submit" id="Backtest" value ="Backtest" name =
"Backtest" onclick ="open_div_res(),openOnglet(event, 'repartition');" >
</div>
</div>
</form>
<div class="tab_back" id ="id_div_res" style="display:none;">
<button class="tablinks"
onclick="openOnglet(event,'repartition')">Result</button> </div>
<script>
function open_div_res(){
document.getElementById("id_div_res").style.display = "block";
document.getElementById('id_div_res').scrollIntoView();
}
</script>
Add type="button" to the button, you don't do this it will trigger a submit.
<button type="button" class="tablinks"
onclick="openOnglet(event,'repartition')">Result</button>
If you mean by clicking this:
<input type="submit" id="Backtest" value ="Backtest" name =
"Backtest" onclick ="open_div_res(),openOnglet(event, 'repartition');" >
You have to change that into a button also
If I do understand this correctly, you want to NOT refresh the page when you click on submit.
Add a listener on your submit button, and, using jQuery
$("#mySubmitButton").on("click", function(event){
event.preventDefault();
// show the div code
$("#myDiv").show();
});
Or, vanilla javascript :
document.getElementById('mySubmitButton').addEventListener('click', function(e){
e.preventDefault();
document.getElementById('myDiv').classList.add('isVisible');
});
this should do the trick !
Try this:
<form action="#" method="post" name= "form1" id = "form1" onSubmit="return false;">
//Code here
</form>

How to get a specific form elements using jQuery

I have a multiple forms in a page and i would like to get the elements of a specific form. For example:
<form class="form" id="1">
<input type="text" name="message" value="message">
<button type="submit" value="submit">Submit</button>
</form>
<form class="form" id="2">
<input type="text" name="message" value="message">
<button type="submit" value="submit">Submit</button>
</form>
How to get the value of message of form id=2...... Thanks in advance
Just use attribute selectors
$('form[id=2]') // get the form with id = 2
.find('input[name=message]') // locate the input element with attribute name = message
.attr("value"); // get the attribute = value
You really shouldn't use raw numbers for ids, let's rename those to form_1 and form_2, then your jquery selector would be:
$("#form_2 [name='message']").val();
Simply query the input from the id of the form you'd like
console.log($('#2 input').val());
//more specific
console.log($('#2 input[name="message"]').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form" id="1">
<input type="text" name="message" value="message">
<button type="submit" value="submit">Submit</button>
</form>
<form class="form" id="2">
<input type="text" name="message" value="message">
<button type="submit" value="submit">Submit</button>
</form>
You can use jQuery, or you can use basic JavaScript to return the message value. With basic JS, you would have to give your form a name, but then could return the message value.
Code:
function getValue() {
var message = document.forms["form_name"]["message"].value;
}
You would then have to return the function when the form is submitted
<form class="form" name="form_name" onsubmit="return getValue()">

Href to another div id on submit in HTML

I have a form which contains a submit button. When I click this submit button I want to go to another div with id home. This is what I am doing now (which is not working):
<input type="submit" class="submit" href="#home" name="action" value="Redirect"/>
For example if I had:
<div id="home"><ul><li>Hello World</li></ul></div>
<input type="submit" class="submit" href="#home" name="action" value="Redirect"/>
This won't work. How can I do this?
You need to have the action of the form be '#home'. Then add a named anchor above the home div.
<html>
<body>
<a name="home"></a>
<div style="height:1500px;">
</div>
<form action="#home">
<input type="submit" value="Home">
</form>
</body>
</html>
href is not a valid attribute for an input element. Try this:
<input type="submit" class="submit" onclick="location.href = '#home'" name="action" value="Redirect"/>
If this is inside of a form, it will submit the form unless you have something preventing that from happening.
just u mention the redirect page in one function.... then that function name calling via onclcik="function_name";
for eg:
function_name
{
some code .......
location.href = 'home.html';
}
<input type="button" onclick="function_name">
your code..........

Categories