How to toggle form visibility dynamically? - javascript

I have page where user can dynamically create new forms. For every new form button is created. Form is hidden by default. I need to toggle form visibility on that button click. Right now i am using javascript code below and its working
$(document).ready(function(){
$("#button1").click(function(){
$("#1").css({"display":"block"});
$("#2").css({"display":"none"});
$("#3").css({"display":"none"});
});
$("#button2").click(function(){
$("#2").css({"display":"block"});
$("#1").css({"display":"none"});
$("#3").css({"display":"none"});
});
...
Now when user create form i manually modify javascript but problem is that i have too many forms right now and ill have even more.
I need solution to bind button for form and toggle its visibility. Any advice is appreciate.
EDIT
Code i am actually using:
while ($row = $result9->fetch_assoc())
{
echo "<input class='btn btn-default' type='button' id='".$row['o_ime']."' name='button' value='".$row['o_ime']."'>";
}
echo "<form class='form-inline' role='form' name='$i' id='$i' style='display:none' action='naruci.php' method='POST' onsubmit='return validateForm()'>";
form elements
echo "</form>";

First of all, you cannot have the same ID in your DOM.
So instead of IDs use classes. And use jquery's class selector.
So to capture the event, just use the class selector.
And also use hide and show jquery APIs to show/hide elements.
$(".new-btn").click(function(){
$("form").hide(); // close all forms
$("this").closest("form").show(); // show parent form
});
And the next thing I notice, for dynamic elements it cannot be captured by normal click event. Use jquery on API.
$(".new-btn").on('click', function(){
$("form").hide(); // close all forms
$("this").closest("form_").show(); // show parent form
// This is the reason it is not working because I forgot the underscore
});
Update:
It should look like this:
while ($row = $result9->fetch_assoc())
{
echo "<input class='btn btn-default' type='button' id='".$row['o_ime']."' name='button' value='".$row['o_ime']."'>";
// We changed the form ID in this section
echo "<form class='form-inline' role='form' name='$i' id='form_".$row['o_ime']."' style='display:none' action='naruci.php' method='POST' onsubmit='return validateForm()'>";
form elements
echo "</form>";
}
In my query I will create an event to capture my button clicks:
$('.btn').on('click', function(){ // Listen all click events of buttons with class `btn`
var id = $(this).attr('id'); // Get ID of focus button
var formName = 'form' + id; // Append form string in the id to match form's ID
$('form').hide(); // Hide all forms
$('#' + formName).show(); // Show exact form
});

you'll find the best way of what you want to do by following the example here in this link
http://www.w3schools.com/jquery/eff_toggle.asp
$("button").click(function(){
$("p").toggle();
});

You can add unique class for all of your forms. Refer this code
<form class="test" id="1"></form>
<form class="test" id="2"></form>
<form class="test" id="3"></form>
$(document).on("click",".test",function(event){
$(".test").css({"display":"none"});
$(this).css({"display":"block"});
});

Just make your own class for display block.
.db{
display:block;
}
Then on your jquery just toggle class.
$("button").click(function(){
$("#1").toggleClass('db');
})

\\对于动态生成的元素需要使用`on`来监听事件的触发
Try the following
$(function(){
//动态构造form元素
//Dynamic construction of form elements
$('#cnf').on('click',function(){
$('#container').append('<div>' +
'<button>toggle</button>' +
'<form><input value="value"></form>' +
'</div>')
});
//通过冒泡监听按钮事件
//The bubble monitor button event
$('#container').on('click','button',function(){
$(this).next().toggle();
})
})
祝顺利!

Related

Why is the button click event not handled?

I'm doing a simple NodeJS-MongoDB todo list application where the todo-items added can be updated. When the edit button is clicked, I'm changing the corresponding element to a form to update it. The edit button when pressed is successfully handled and is converted to a form, whereas when the update button is clicked it is not handled by the event listener and the default refresh action takes place. Why?
Javascript Part:
$(document).ready(function(){
$('.update').on('click', function(){
var id = $(this).parent().find('input:hidden');
var item = $(this).parent().find('input:text');
var priority =$(this).parent().find('select option:selected');
var todo = {item: item.val(), priority: priority.val()}
$.ajax({
type: 'PUT',
url: '/todo/' + id.val(),
data: todo,
success: function(data){
location.reload();
}
});
});
$('.edit').on('click', function(){
var id = $(this).parent().find('input:hidden');
var item = $(this).parent().find('b');
$(this).parent().html(
"<form>"+
"<input type = 'text' name = 'item' value='" + item.text() + "' required />"+
"<select name = 'priority' required>"+
"<option value = 'high'> High </option>"+
"<option value = 'medium'> Medium </option>"+
"<option value = 'low'> Low </option>"+
"</select>"+
"<input type = 'hidden' value='" + id.val() + "'/>"+
"<button class = 'update'> Update Item </button>"+
"</form>");
});
});
HTML Part:
<ul>
<% for(var i=0; i < todos.length; i++){ %>
<li>
<input type = "hidden" value = <%= todos[i]._id %> />
<b> <%= todos[i].item %> </b>
<button class = "edit"> 📝 </button>
</li>
<% } %>
</ul>
I think this will solve your problem
$(document).on('click', '.update', function(){
//Rest of your code
})
If your page was dynamically creating elements with the class name dosomething you would bind the event to a parent which already exists, often "document"
$(document).on('click', '.update', function(){
// what you want to happen when click
// occurs on elements that match '.update'
});
Or you can use a parent DOM element, That always remain in your page load Eg:
$('ul').on('click', '.update', function(){
// do something here
});
You can put console.log(); to double check if it is going in. Button in a form's default action is going to form's action page which you don't have and you are not doing any POST, GET etc. with form, you are doing it with ajax. If you don't want to use form's functionality, you can just give type=button to button. If you are going to not use the form to post, get or anything in the future, removing the form tag is another option.
EDIT
After other answers, I noticed that the correct answer can be given by mixing my and their answers. So I decided to add this part too. You are giving onClick eventhandler before the DOM element was created. You must give event handler after creating the element. Your options here are:
Adding the whole .update onClick inside .edit onClick's bottom.
Giving onClick event handler to an object which was already created before any javascript action.
$(document).on('click', '.update', function(){
//update's onClick actions here
}

How to use Javascript to validate dynamically generated PHP form?

I've created a form using PHP in which the user has to click on a radio button before clicking on the button to submit the form. It looks as follows:
<form name="films" action="showing.php" method="post">
<table id="filmtable">
<tr><th>Title</th><th>Length</th><th>Description</th><th>Poster</th><th>Required</th></tr>
<?php
//Loop through every row returned by $result query to display it in table.
while ($newArray = mysql_fetch_array($result)){
$title = $newArray['title'];
$length = $newArray['length'];
$description = $newArray['description'];
$image = $newArray['image'];
//Echo statements will display query results on screen.
echo "<tr><td>$title</td><td>$length</td><td>$description</td>";
echo "<td><image src=\"$image\"</td>";
echo "<td><input type=\"radio\" id='wanted' name=\"wanted[]\" value='$title'></td></tr>";
}
// if (! array_key_exists($_POST['wanted[0]'], $result)){
// echo "Select it.";
//}
?>
</table>
<input type="submit" onsubmit = 'return validate()' value="Select Film">
</form>
As a validation measure I created the following in Javascript with the aim of preventing the user from submitting the form if they have not selected a radio button:
<script>
function validate(){
var radio = document.getElementById('wanted').checked;
if(radio=="")
{
alert("Please select a film to continue making a booking.");
return false;
}
return true;
}
</script>
The script prevents the user from submitting the form if no selection has been made from the radio boxes as intended. However, it will only allow the form to be submitted if the first radio box is selected. Selecting any button other than this one will cause the submit attempt to fail. What changes should I make to the JS to rectify this situation?
This PHP fetch loop attributes multiple times the same id="wanted" to many radio buttons.
An Id should be unique.... So it's a bad practice.
Remove the id and add a class instead:
echo "<td><input type=\"radio\" class=\"wanted[]\" name=\"wanted[]\" value='$title'></td></tr>";
Then, the use of jQuery saves pain...
Within your submit script:
if(!$('.wanted').prop("checked")){
alert("Please select a film to continue making a booking.");
return;
}
Add this jQuery lib call in your head:
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
EDIT - See comments
Function validate should be this:
function validate(){
var wantedChecked=$(".wanted:checked");
if (!wantedChecked.prop("checked")){
console.log("false");
return false;
}else{
console.log("true");
return true;
}
}
getElementById returns the first element matching the selector. If you just want to verify that any of them were checked, you could do something like:
var anyChecked = document.querySelectorAll('[name=wanted]:checked').length > 0;

How to Replace a Div with another Div but only once

I am trying to replace a div with another div onclick using the code below. It works fine for one instance. However, the problem is when the class appear more than once which is the case for me (multiple instances)it obviously changes all instance as they have the same class name.
Is there a way to make it only change the clicked instance? Thanks
HTML
<div id="test"></div>
JavaScript (dynamically creating HTML)
var html =
'<form action="test.php" method="get" class="myForm">' +
'<input type="hidden" name="mID" value="' + this.id + '"/>' +
'<input type="image" class="send" src="this.image" name ="send" alt="submit"/>' +
'</form>';
$('div#test').append(html);
$("#test").on('click', '.send', function(e) {
e.preventDefault();
var $form = $(this).closest('form');
$.get($form.attr("action"),
$form.find(":input").serializeArray(),
function(data) {
$('.myForm').replaceWith('<div class="myForm2"><img src="Icons/PNG/tick 2.png" alt="submit"/></div></div>');
});
});
$("#test").on('submit', '.myForm', function(e) {
return false;
});
SOLUTION;
Instead of;
$('.myForm').replaceWith('<div class="myForm2"><img src="Icons/PNG/tick 2.png" alt="submit"/></div></div>');
CORRECT WAY;
$form.replaceWith('<div class="myForm2"><img src="Icons/PNG/tick 2.png" alt="submit"/></div></div>');
You're already most of the way there with $form = $(this).closest('form'); but for some reason you started selected all the forms instead by using $('.myForm'), so
replace
$('.myForm').replaceWith(...
with
$form.replaceWith(...
First of all, you are not replacing a div, you are replacing a form (with class .myForm). As this form is inside the div you are clicking on when you want to change your form you could use:
$(this).find(".myForm").replaceWith...
$(".targetClass").click(function(){
var theDivBeingClicked = $(this);
//Do something
})
Simple!
I am no JQuery Expert, but we doit the traditional way!
var elements = document.getElementByID('test')
we would have elemements[0] and elements[1] .... everything with the id="test" inside. but only the first element needs to be replaces.
so, our choice falls on elements[0].
$('.myForm').replaceWith(.....)
take myForm away, and add the elements array number you'd like having to be replaces, then it's always this element in the doc that is being replaces.
have fun!

Updating an input with the value of a href Jquery

My link:
<?php echo $r['price']; ?>
and my non-working jquery:
$('a[href="buyorderprice"]').click(function(){
$('#sellprice').val($('#buyorderprice').attr('href'))
});
The price value is just a number which is working. Also, I don't want the page to reload when I click the button just update the sellprice input which is:
<input type="text" class="form-control" id="sellprice" name="sellprice" value="<?php echo
$coinTicker->price($coin2[1] , 'sell'); ?>">
the cointicker is the default value of a random number
Using javascript / Vanilla JS, you can achieve it like this:
var a = document.getElementById('buyorderprice');
a.addEventListener('click',setValueNow);
function setValueNow(e) {
e.preventDefault();
var b = document.getElementById('sellprice').value = document.getElementById('buyorderprice').getAttribute('href');
}
Here's a DEMO
Try ...
$("#buyorderprice").click(function() {
$('#sellprice').val($('#buyorderprice').attr('href'));
});
... since #buyorderprice is the id.
To make it more workable, change the href to read href="#" and use value ...
<?php echo $r['price']; ?>
... then you don't have to be concerned about the default anchor functionality that will try to navigate to the price. Then, this line would become ...
$('#sellprice').val($('#buyorderprice').data('value'))
The value of the input is changed, but then your page is reloaded and you don't see what changed. So you need to stop the page from reloading when you click the button.
Here is the code to do that:
$("#buyorderprice").click(function(e) {
e.preventDefault();
$('#sellprice').val($('#buyorderprice').attr('href'));
});
jsFiddle demo here

How to dynamically add List items in jQuery

I am developing an mobile app in which i want to populate ListView once the user fill up the form and click on submit button.
I know how to give List View in jQuery but how to populate items in it dynamically at run time?
Are you looking for something like this?
jsFiddle Demo:
HTML:
<div id="listView"></div>
<input type="button" id="mybutt" value="Submit" />
javascript/jQuery:
$('#mybutt').click(function() {
var out = '<ul><li>Item One</li><li>Item Two</li><li>Item Three</li></ul>';
$('#listView').html(out);
});
Responding to your comment: "what i need is on click of button form gets submitted and firstname which user enters on form will get added in list"
First, you need to remain on the page after the form was submitted. To do that, you should add e.preventDefault(); in your submit routine:
$( "#target" ).submit(function( event ) {
//Manually collect form values and
//Use ajax to submit form values here (see notes at bottom)
event.preventDefault();
});
Next, you want to get the data that was in the desired field, and add that to the <ul>. Therefore, change the above like this:
$( "#target" ).submit(function( event ) {
var fn = $('#fname').val();
$('ul').append('<li>' +fn+ '</li>');
//Manually collect form values and
//Use ajax to submit form values here (see notes at bottom)
event.preventDefault();
});
For the AJAX bit, see this post for tips.
Note that you can use $('#formID').serialize(); to quickly serialize all form data.
js fiddle:
http://jsfiddle.net/7PzcN/1/
html:
<div id="listView"></div>
<input type="text" name="firstname"/>
<input type="text" name="lastname"/>
<input type="button" id="mybutt" value="Submit" />
jquery:
$('#mybutt').click(function() {
var out = '<ul>';
$("input[type=text]").each(function() {
out += "<li>" + $(this).val() + "</li>";
});
out += "</ul>";
$('#listView').html(out);
});

Categories