How to Replace a Div with another Div but only once - javascript

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!

Related

JQuery Not Triggering On Button.click

I've written some code that should check a textbox (ID tfa_1) to see if its empty or contains text, this should trigger on a next page button (wfpagenextID6) being clicked.
I've tried replacing my script with an alert("test.") and it dosent appear, so im assuming I have my trigger wrong but I cannot work out what I have done wrong!
My HTML that defines the textbox is below:
<input type="text" id="tfa_2685" name="tfa_2685" value="" placeholder="" title="Previous Surname (if applicable) " class="">
and the button is
<input value="Next Page" type="button" class="wfPageNextButton" wfpageindex_activate="7" id="wfPageNextId6" style="visibility: visible;">
Both of these are generated and I cannot change them!
My Script is:
<script>
$(document).ready(function(){
$('#wfPageNextId6').click(function(){
var inp.Val= $("#tfa_2685").val();
if (inp.val().length > 0) {
alert("Test.");
}
});
})
</script>
An identifier ( variable ) must not contains dots. ( see more details ECMAScript specification in section 7.6 Identifier Names and Identifiers)
the next variable declaration is wrong
var inp.Val= $("#tfa_2685").val();
to fix this
var inp = $("#tfa_2685");
if you want to assign value to inp variable, you should just do: var inp = $("#tfa_2685").val();
And then call to inp.val() just replace with inp, for inp is not jQuery object so it doesn't have val() method
You have syntax, try this:
$(document).ready(function(){
$('#wfPageNextId6').click(function(){
var inpVal= $("#tfa_2685").val();
if (inpVal.length > 0) {
alert("Test.");
}
});
});
https://jsfiddle.net/cua40s80/

How to toggle form visibility dynamically?

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();
})
})
祝顺利!

Jquery multiple plus/minus script

I have multiple forms on a page and also multiple input boxes with plus/minus signs.
I'm having trouble to get those input boxes to work seperately. Probably because of some wrong/same id's or something like that or maybe a wrong setup of my code. The thing is I can't find my error in the code and I don't get any errors in my console.
What I have:
function quantity_change(way, id){
quantity = $('#product_amount_'+id).val();
if(way=='up'){
quantity++;
} else {
quantity--;
}
if(quantity<1){
quantity = 1;
}
if(quantity>10){
quantity = 10;
}
$('#product_amount_'+id).val(quantity);
}
And my html:
//row 1
<div class="amount"><input type="text" name="quantity" value="1" id="product_amount_1234"/></div>
<div class="change" data-id="1234">
+
-
</div>
//row 2
<div class="amount"><input type="text" name="quantity" value="1" id="product_amount_4321"/></div>
<div class="change" data-id="4321">
+
-
</div>
I thought something like this would do the trick but it doesn't :(
$(document).ready(function(){
$('.change a').click(function(){
var id = $(this).find('.change').data('id');
quantity_change(id)
});
});
Any help greatly appreciated!
You should use closest() method to get access to the parent div with class change, then you can read the data attribute id's value.
var id = $(this).closest('.change').data('id');
alert(id);
Since you are already binding the click event using unobutrusive javascript, you do not need the onclick code in your HTML markup.
Also your quantity_change method takes 2 parameters and using both, but you are passing only one. You may keep the value of way in HTML 5 data attributes on the anchor tag and read from that and pass that to your method.
<div class="change" data-id="1234">
+
-
</div>
So the corrected js code is
$(document).ready(function(){
$('.change a').click(function(e){
e.preventDefault();
var _this=$(this);
var id = _this.closest('.change').data('id');
var way= _this.data("way");
quantity_change(way,id)
});
});
Here is a working sample.

How to send multiple values from a checkbox input

I am trying to collect multiple pieces of data from a checkbox, but I am unsure of how to do this. Right now I have:
<input tabindex="1" type="checkbox" name="friend[]" id="{{$friend}}" value="{{$friend}}" style="display:inline-block;">
Which allows me to collect an id (contained in {{$friend}}) that I need. But I also need the name associated with this id. Is there a way to collect multiple values from a single checkbox? I would need this because I am collecting the data and moving to another form without changing the view. This would be used for javascript which would print out stuff in the view as it is checked (i.e. the id and name).
Here is the javascript:
<script>
$(document).ready(function(){
var callbacks_list = $('.callbacks ul');
$('.facebook-friends-larger input').on('ifChecked', function(event){
callbacks_list.prepend('<li><img src="https://graph.facebook.com/'+this.id+'/picture" alt="" height="50" width="50"><span id="#'+this.id+'">#' + this.id + '</span> is ' + event.type.replace('if', '').toLowerCase() + '</li>');
});
$('.facebook-friends-larger input').on('ifUnchecked', function(event) {
callbacks_list.find('span#'+ this.id).closest('li').remove();
console.log(this.id);
});
});
</script>
Any ideas? Thank you for your help.
Try this this will be helpyou..
$("input[type=checkbox]").change(function(){
alert($(this).val()); //get a val
alert($(this).attr('name')); //get a value of name attribute
});
Fiddle here
If you have the access to the username before the page is loaded (and is therefore able to inject it into the DOM without making ajax queries after pageload or user action), you can store them in HTML5 data- attributes, for example, data-name in the following format:
<input tabindex="1" type="checkbox" name="friend[]" id="{{$friend}}" value="{{$friend}}" data-name="{{name}}" style="display:inline-block;">
You can access the name by simply calling the .data() method in jQuery, i.e. $('input').data('name').
Use:
var name = $("#checkbox-id").attr("name"); // Use whatever method you have to target the checkbox
and so on to get the other values
Try this
HTML
<input tabindex="1" type="checkbox" name="friend[]" id="123" value="{{$friend}}" style="display:inline-block;">test
JS
$(document).ready(function(){
$("#123").change(function(){
$(this).val(); //get a val
console.log($(this).attr('name')); //get a value of name attribute
});
});
FIDDLE

Refactor replace within jquery

Working version http://jsfiddle.net/uxBZN/
Would it be better to just replace password or text within the type (type="password") parameter of html input tag, instead of the whole html input type tag, as seen below?
$("#unhide_typing").live("click", function(){
var security_answer = $("#security_answer").val();
var hnumber = $("#hnumber").val();
if ($('#unhide_typing').is(':checked')) {
$("#security_answer").replaceWith('<input type="text" name="answer" value="'+security_answer+'" id="security_answer">');
$("#hnumber").replaceWith('<input type="text" name="hnumber" value="'+hnumber+'" id="hnumber">');
} else {
$("#security_answer").replaceWith('<input type="password" name="answer" value="'+security_answer+'" id="security_answer">');
$("#hnumber").replaceWith('<input type="password" name="hnumber" value="'+hnumber+'" id="hnumber">');
}
});
This needs to work with IE 7/8 and I want to retain the currently entered text.
Yes, you can do that.
$("#unhide_typing").live("click", function(){
var security_answer = $("#security_answer").val();
var hnumber = $("#hnumber").val();
var type = $(this).is(':checked') ? "text" : "password";
$("#security_answer").replaceWith('<input type="' + type + '" name="answer" value="'+security_answer+'" id="security_answer" />');
$("#hnumber").replaceWith('<input type="' + type + '" name="hnumber" value="'+hnumber+'" id="hnumber" />');
});
Note: Inside the handler you can use this to refer to #unhide_typing and also if you are using jQuery ver 1.7+ then it is preferrable to use on instead of live.
Replacing some properties of HTML elements with jQuery could be tricky on older versions. I recommend you to stay with .prop() function and do not replace DOM elements.
So, your code should be this:
$("#unhide_typing").live("click", function(){
var security_answer = $("#security_answer").val();
var hnumber = $("#hnumber").val();
if ($('#unhide_typing').is(':checked')) {
$('#security_answer').prop('type', 'text');
$('#hnumber').prop('type', 'text');
} else {
$('#security_answer').prop('type', 'password');
$('#hnumber').prop('type', 'password');
}
});​
Yes, it's better to just replace the type for a number of reasons:
Better performance (an element isn't getting removed and then a new one getting created/inserted into the DOM)
Doesn't break the browser's built-in undo mechanism (probably not critical for this use-case, but perhaps it is in others).
Any other event handlers bound to the original input won't get removed
Just make sure you use jQuery's .prop() method rather than .attr():
http://jsfiddle.net/uxBZN/2/

Categories