remove last inserted element by php in JQUERY - javascript

I have container called interest_type_container. In which 2 fields are there interest type and period.
HTML:
<div id="interest_type_container">
<label class="col-md-4">Interest Type *</label>
<select name="interest_type[]" class="form-control">
<option value="">Select</option>
// Some options...
</select>
<label class="col-md-4">Interest Period *</label>
<select name="interest_period[]" class="form-control">
<option value="">Select</option>
// Some options...
</select>
</div>
<button type="button" name="add_more_interest" id="add_more_interest">Add</button>
<button type="button" name="remove_more_interest" id="remove_more_interest">Remove</button>
JQUERY:
I this I have add and remove functions. So, when user clicks on add it will add those two fields from ajax request.
AJAX:
$("#add_more_interest").on('click',function(){
$.ajax({
type: 'post',
url: '/transaction/fetch_interest_type_and_period',
success: function (res) {
$('#interest_type_container').append(res);
}
});
});
And when user clicks on remove. It should remove last inserted 2 fields. I tried with this. But, it's not working.
$("#remove_more_interest").on('click', function(){
$('#interest_type_container:last-child', this).remove();
});

Here is an example of something you could do given the HTML (pairs of labels and selects with no surrounding element) that you have:
$("#remove_more_interest").on('click', function () {
var labelLength = $('#interest_type_container > label').length - 1;
var selectLength = $('#interest_type_container > select').length - 1;
$('#interest_type_container > label').eq(labelLength).remove();
$('#interest_type_container > label').eq(labelLength - 1).remove();
$('#interest_type_container > select').eq(selectLength).remove();
$('#interest_type_container > select').eq(selectLength -1).remove();
});
This is using straight up brute force though, there may be better, more elegant ways to accomplish this.
http://jsfiddle.net/jayblanchard/uohc23xd/

You have to specify the tag type and use "last" selector
$(document).on('click', '#remove_more_interest', function(){
$('#interest_type_container').children('label:last').remove();
$('#interest_type_container').children('select:last').remove();
});
You can test your selector from your web browser console by hitting F12 and select console tab. Wrote these lines and you'll see what it returns. This Console is your best friend!
Your onclick method is not good! The complete code HERE
<html><head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).on('click', '#remove_more_interest', function(){
$('#interest_type_container').children('label:last').remove();
$('#interest_type_container').children('select:last').remove();
$('#interest_type_container').children('label:last').remove();
$('#interest_type_container').children('select:last').remove();
});
</script>
</head><body>
<div id="interest_type_container">
<label class="col-md-4">Interest Type *</label>
<select name="interest_type[]" class="form-control">
<option value="">Select</option>
</select>
<label class="col-md-4">Interest Period *</label>
<select name="interest_period[]" class="form-control">
<option value="">Select</option>
</select>
</div>
<button type="button" name="remove_more_interest" id="remove_more_interest">Remove</button>
</body></html>

You can do one thing. When you append the result, put it in a container e.g.
$('#interest_type_container').append('<span class="appended_res">'+res+'</span>');
After that, you can use class 'appended_res' to remove the elements.

Thank you guys for your efforts. I come up with a solution. And it works.
Dynamic generated elements, which are coming from ajax. I put those elements under new_inserted_elements ID.
Now in, JQUERY:
$("#remove_more_interest").on('click', function(){
$('#new_inserted_elements').remove();
});
It removes last inserted id, those are my 2 elements.

Related

How to using eq() while dealing in Div tag - Jquery

I am having this following HTML code,
<div class="row add_all">
<div class="col-lg-12">
<span class="pf-title">Title</span>
<div class="pf-field">
<input type="text" placeholder="Write Something here.." />
<button class="add-subject" type="button">
<i class="fa fa-plus"></i>
</button>
<div style="display: inline-flex; margin-bottom: 22px;">
<select data-placeholder="Allow In Search" id="input_data1" style="width: 70%; margin-right: 10px;">
<option value="">Level</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select data-placeholder="Allow In Search" id="input_data2" style="width: 70%; margin-right: 10px;">
<option value="">Level</option>
<option value="I">I</option>
<option value="II">II</option>
<option value="III">III</option>
</select>
</div>
</div>
</div>
<div class="col-lg-12">
<div class="sodmzs"></div>
</div>
<div class="col-lg-12">
<button type="submit">Update</button>
</div>
</div>
Where I am having one textbox in the first row and two combo boxes in the second row. When the user will click on plus icon, another textbox in the first row and two combo boxes in the second row will get generated and added. User can generate as many as they wants (1 textbox and 2 combo boxes) via clicking on the add icon.
To get the whole values from the generated div tag, I wrote the following code,
$("#form_id_name").submit(function(e){
e.preventDefault();
var json_data = [];
$(".add_all").each(function(){
title = $(this).children().eq(0).find('input').val();
level_no = $(this).children().eq(0).find("option:selected").text();
level_ro = $(this).children().eq(1).find("option:selected").text();
var single_data = {"title":title, "level_no":level_no, "level_ro":level_ro}
json_data.push(single_data);
});
var string_data = JSON.stringify(json_data);
console.log(string_data);
*ajax code*
But this code doesn't help me to get the desired output that I want. Can you help me out to know where I am doing it wrong ?
Thanks.
NOTE: I am appending the HTML code using $('.sodmzs').append(fieldHTML); where fieldHTML contains html code encapsulated in single quotes.
I believe you're using too many methods to access the DOM elements, this code is a simplified version, I tested it in codepen and returns:
$("button").click(function (e) {
e.preventDefault();
var json_data;
$(".add_all").each(function () {
title = $(this).find("input").val();
level_no = $(this).find("option:selected:first").text();
level_ro = $(this).find("option:selected:last").text();
json_data = {
title: title,
level_no: level_no,
level_ro: level_ro
};
});
json_data = JSON.stringify(json_data);
console.log(json_data);
});
// "{'title':'my title','level_no':'1','level_ro':'III'}"
It looks like you're pushing single_data onto json_data before assigning it a value. Due to hoisting, single_data gets declared at the top of the function - so it's defined and you won't get an error. But, you also won't get your data.
Change
json_data.push(single_data);
var single_data = {"title":title, "level_no":level_no, "level_ro":level_ro}
to just
json_data.push({"title":title, "level_no":level_no, "level_ro":level_ro});
Also, you could clean up the code a bit by adding classes to your inputs & selects. So this:
title = $(this).children().eq(0).find('input').val();
could be simplified to this:
title = $(this).find(".titleinput").val();
It'll also be more robust if you change the underlying markup.

How to change the content of a page with javascript based on select input?

Let's say I have a webpage like this:
<div style="margin:auto;text-align:center;padding-top:10px;">
<form action="" method="POST">
<p style="text-align:center;">
<select>
<option value="blogs">blogs.php</option>
<option value="portfolio">portfolio.php</option>
<option value="contact">contact.php</option>
<option value="home">home.php</option>
</select>
</p>
<p style="text-align:center;">
<input type="submit" name="submit" value="Submit"/>
</p>
</form>
</div>
<div class="pagetitle">
<h5>Option Value (for example blogs)</h5>
</div>
As you can see, a user can choose from 4 options in the select menu. I want to know ,is there any way to change the content of this div => <div class="pagetitle"> with javascript onsubmit ? For example if a user choosed blogs.php ,the h5 tag will change to <h5>blogs</h5> & if he choosed portfolio.php ,it'll be changed to <h5>portfolio</h5> . I really appreciate if you know how to do this ... thanks in advance!
You'll need to start by adding a javascript function to handle the event.
<script>
function changedSelect(x)
{
document.getElementById('pageTitleDiv').innerHTML = "<h5>"+x+"</h5>";
}
</script>
And then you'll need to trigger the event when the "select" box is changed.
<select onchange="changedSelect(this.value)">
Finally, I would give the div an "ID" so that it is specifically altered.
<div class="pagetitle" id="pageTitleDiv">
You need to bind a jquery .change event to the select element and have it's selected value populated as the text of h5 tag
<script>
$(document).ready(function(){
$('select').change(function()
{
$('h5').text($(this).val());
}).change(); // this is optional - it basically invokes the change event as soon as the function is registered.
});
</script>
Example : https://jsfiddle.net/DinoMyte/6x80vabm/4/
Using vanilla javascript, I added an id to the select element and used javascript to get the value of the select option, then I updated the element on the DOM.
<div style="margin:auto;text-align:center;padding-top:10px;">
<form action="" method="POST">
<p style="text-align:center;">
<select id="myselect">
<option value="blogs">blogs.php</option>
<option value="portfolio">portfolio.php</option>
<option value="contact">contact.php</option>
<option value="home">home.php</option>
</select>
</p>
<p style="text-align:center;">
<input type="submit" name="submit" onclick="myFunction()" value="Submit"/>
</p>
</form>
</div>
<div class="pagetitle">
<h5>Option Value (for example blogs)</h5>
</div>
<script>
function myFunction() {
var x = document.getElementById("myselect").selectedIndex;
var _value = document.getElementsByTagName("option")[x].value;
document.getElementsByTagName('h5')[0].innerText = _value
}
</script>
Note: This can be achieved in several ways using vanilla JS or libraries, but I think this answers your question.

Onchange inside onchange jquery

Im having trouble having code onchange inside onchange event.
some works and some dont work due to that.
<script>
$(document).on('change', '.sellkop', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#text_container").after(price_option());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").css({"display": 'none'
});
};
});
$('#category_group').on('change', function() { // this is select options
if ($(this).val() == 101) {
$("#underKategory").css({"display": 'none'});
$("#modelcontainer").remove();
$(".toolimage").css({ "display": 'block'});
$('.sellkop').on('change', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").css({"display": 'block'});
$(".toolimage").css({"display": 'block' });
} else {
$(".toolimage").css({"display": 'none'});
}
});
} else {
$(".bilar").remove();
$(".toolimage").css({ "display": 'none'});
}
if ($(this).val() == 102) {
$(".houses_container").remove();
$(".toolimage").css({"display": 'none'});
$("#underKategory").css({"display": 'inline-block'});
$("#modelcontainer").remove();
}
///............many other values continue
});
</script>
i know there is better way to manage this code and simplify it , how can i do it ?
EDIT:
what i want is : if i select an option , then get values to that option, then under this category option there is radio buttons , then every check button i need to get some data displayed or removed
here is a fiddle there looks my problem by jumping from categories when i select buy or sell , so
if i select category-->check buy -->then select others . i dont get same result as if i select directly cars ---> buy
I have never resorted to even two answers before (let alone three), but based on all the comments, and in a desire to keep things simple another solution is to data-drive the visibility of other items based on selections, using data- attributes to store the selectors on the options and radio buttons.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/28/
e.g the HTML for the select becomes
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101' data-show="#sellbuy,.cars,.toolimage,#licenscontainer">cars</option>
<option value='102' id='cat102' data-show="#sellbuy,#underKategory">others</option>
</select>
and the radio buttons like this:
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' data-show="#price_container,.cars,.toolimage"/>
The code becomes very simple then, simply applying the filters specified in the selected items.
$(document).on('change', '.sellkop', function () { // this is radio button
// Hide defaults
$("#price_container,.cars,.toolimage").hide();
// Show the items desired by the selected radio button
$($(this).data("show")).show();
});
$('#category_group').on('change', function () { // this is select options
// Get the various possible data options and decide what to show/hide based on those
var $this = $(this);
var value = $this.val();
// Get the selected option
var $li = $('option[value='+ value+']', $this);
// Hide all the defaults first
$('#licenscontainer,.cars,.toolimage,.sell,#underKategory').hide();
// Now show any desired elements
$($li.data('show')).show();
// Fire change event on the radio buttons to ensure they change
$('.sellkop:checked').trigger('change');
});
This is a very generic solution that will allow very complex forms to turn on/off other elements as required. You can add data-hide attributes and do something similar for those too if required.
Note: This was an attempt to fix the existing style of coding. I have posted an alternate answer showing a far simpler method using hide/show only.
A few problems.
If you must nest handlers, simply turn them off before you turn them on. Otherwise you are adding them more than once and all the previously recorded ones will fire as well.
Your HTML strings are invalid (missing closing </div>)
You can simply use hide() and show() instead of all the css settings. You should use css styling for any specific element styling requirements (e.g. based on classes).
You need to replace specific divs, rather than keep using after, or you progressively add more html. For now I have use html to replace the content of the #text_container div.
HTML in strings is a maintenance nightmare (as your example with missing </div> shows). Instead use templates to avoid the editing problems. I use dummy script blocks with type="text/template" to avoid the sort of problems you have found. That type means the browser simply ignores the templates.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/17/
HTML (with templates)
<script id="saljkop">
<div class='sex sell' id='sellbuy' >
<label ><input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked'/> Sell </label>
<label ><input id='rk' type='radio' class='radio sellkop' value='k' name='type'/>buy</label>
</div>
</script>
<script id="price_option">
<div class="container" id = "price_container">
<div>
<label><input class="price_option" name="price_opt" value="1" type="radio"/> Fix </label>
<label class="css-label"><input class="price_option" name="price_opt" value="2" type="radio"/> offer </label>
</div>
</div>
</script>
<script id="cars">
<div class="cars" >
<div id="licenscontainer" ><div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</script>
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">textttttt</div>
New jQuery code:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#sellbuy").after($('#cars').html());
$("#text_container").html($('#price_option').html());
$("#underKategory").hide();
$(".toolimage").show();
$('.sellkop').off('change').on('change', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").show();
$(".toolimage").show();
} else {
$(".toolimage").hide();
}
});
} else {
$(".cars").remove();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#text_container").html($('#price_option').html());
$(".toolimage").hide();
$("#underKategory").show();
}
///............many other values continue
});
Now if you prefer to not nest handlers (recommended), just add to your existing delegated event handler for the radio buttons:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
$("#licensenumber_c").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
$(".toolimage").hide();
};
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/20/
Note: This was a second answer, hoping to simplify the overall problem to one of hiding/showing existing elements. I have posted a third(!) answer that takes it to an even simpler scenario using data- attributes to provide the filter selections.
I am adding a second answer as this is a complete re-write. The other answer tried to fix the existing way of adding elements dynamically. I now think that was simply a bad approach.
The basic principal with this one is to have very simple HTML with the required elements all present and simply hide/show the ones you need/ Then the selected values are retained:
This uses the multi-structure to effectively hide.show the licence field based on two separate conditions.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/23/
Html (all element s present, just the ones you do not need hidden):
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
<div class='sex sell' id='sellbuy' style="display: none">
<label>
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' />Sell</label>
<label>
<input id='rk' type='radio' class='radio sellkop' value='k' name='type' />buy</label>
</div>
<div class="cars" style="display: none">
<div id="licenscontainer">
<div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">
<div class="container" id="price_container" style="display: none">
<div>
<label>
<input class="price_option" name="price_opt" value="1" type="radio" />Fix</label>
<label class="css-label">
<input class="price_option" name="price_opt" value="2" type="radio" />offer</label>
</div>
</div>
</div>
jQuery:
$(document).on('change', '.sellkop', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#price_container").show();
$(".cars").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").hide();
$(".cars").hide();
$(".toolimage").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").hide();
$("#sellbuy").show();
$(".cars").show();
$("#underKategory").hide();
$(".toolimage").show();
$('#licenscontainer').show();
} else {
$('#licenscontainer').hide();
$(".cars").hide();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").hide();
$("#sellbuy").show();
$(".toolimage").hide();
$("#underKategory").show();
$(".cars").hide();
}
$("#price_container").toggle($("#rs").is(':checked'));
///............many other values continue
});

Show multiple fields based on dropdown - doesn't work when other dropdowns are on page

I previously asked about showing mulple fields based on a dropdown which used JQuery:
Show multiple fields based on dropdown
However when I have other dropdown fields on my page, this no longer works. I did wonder it it was interfering with other JavaScript / JQuery elements, but removing those didn't correct the issue. I've also tried putting the elements into separate ULs and DIVS with no luck. Can someone help?
In my example, when selecting 'Taking over existing Mobile' it should display 'Existing Mobile No', however it won't when the 'Existing PC' is still listed on my page.
HTML:
<ul>
<li>
<label for>NS - Mobile</label>
<select class="selectmenu" id="_1_1_81_1" name="_1_1_81_1" onchange="markDirty();">
<option value="" ><None></option>
<option value="Mobile" >Mobile</option>
<option value="Blackberry" >Blackberry</option>
<option value="otheros" >Taking over Existing Mobile</option>
</select>
</li>
<li class="osother">
<label for>NS - Existing Mobile No</label>
<input class="valueEditable" TYPE="text" name="_1_1_83_1" title="NS - Existing Mobile No" id="_1_1_83_1" value="[LL_FormTag_1_1_83_1 /]" size="12" MAXLENGTH="11" ONCHANGE="markDirty();">
</li>
<li>
<label for>NS - Existing PC</label>
<select class="selectMenu" id="_1_1_84_1" name="_1_1_84_1" onchange="markDirty();">
<option value="" ><None></option>
<option value="Yes" >Yes</option>
<option value="No" >No</option>
</select>
</li>
</ul>
JQ:
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("select").change(function () {
$("select option:selected").each(function () {
if ($(this).attr("value") == "otheros") {
$(".osother").show();
} else {
$(".osother").hide();
}
});
}).change();
});
</script>
CS:
.osother{display:none;}
My other JQ is here and collapses sections on the page - maybe irrelevant:
<script type="text/javascript" src="[LL_SUPPORTPATH /]core/jquery.collapsible.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
//collapsible management
$('.collapsible').collapsible({
defaultOpen: 'section1,section2,section3,section4,section5'
});
});
</script>
There is also some JavaScript here and there that adds in TABS and Date dropdowns, but have tested without these elements and it seems still not to work.
Basically you're looping through every select in the page and checking for their values, when you actually should observe just the one with ID _1_1_81_1.
Also, you can simplify your code:
$(function () {
// Observe the particular select for changes in its value.
// As every element in the page should have its on ID, you can
// select it straight away (omitting the type - select).
$("#_1_1_81_1").on("change", function () {
// Toggle the input visibility based on the selected value.
// The .val() method works here just like for every type of
// input. You don't need to go through all the select options
// and test their values.
$(".osother").toggle($(this).val() == "otheros");
});
});
Demo
jQuery .toggle()
Note: This answer is based on the code you provided. If there are any other requirements or code involved, you should state it in the question.

how display a jquery validate message inside a div tag

I am successfully validating a required field using jQuery Validate method. Everything works fine but I want to display the error message inside ia div tag which an option to make the error disappear after 10 or 20 sec of showing it, basically like a auto hide.
here is the markup I have created
<script type="text/javascript">
$(document).ready(function(){
$("#cForm").validate({
rules: {
PaymentMethod: {
required: true
}
,ShippingMethod: {
required: true
}
},
messages: {
PaymentMethod: {
required:" Select a payment method!"
}
,ShippingMethod: " Select a shipping method!."
}
});
});
</script>
<sytle="text/css">
#ship-msg, #pay-msg {display:none; background:url("/image/req.gi") no-repeat left center transparent;}
.msg { color:#000;}
</style>
<form id="cForm" method="post" action="/pay.html">
<div class="ship-options">
<label for="ShippingMethod">Shipping Method</label>
<select id="ShippingMethod" name="ShippingMethod" >
<option value="">Choose Shipping Method</option>
<option value"UPS-GROUND">UPS GROUND</option>
<option value"UPS-1DAY">UPS 1DAY</option>
<option value"UPS-2DAY">UPS 2DAY</option>
</select>
<div id="ship-msg><div class="msg"> // display the error messgae here </div>
</div>
<div class="pay-options">
<label for="PaymentMethod">Payment Method</label>
<select id="PaymentMethod" name="PaymentMethod" >
<option value="">Choose Paymenet Method</option>
<option value"VISA">VISA</option>
<option value"MASTERCARD">MASTERCARD</option>
<option value"AMEX">AMERICAN EXPRESS</option>
</select>
<div id="pay-msg><div class="msg"> // display the error messgae here </div>
</div>
<input type="submit" value="Continue" id=" />
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.min.js"></script>
and so when some clicks the continue button and if the methods are not selected display them display the respective divs and its message
I know i am missing something
Thanks and appreciate it
You misspelled the opening <style> tag. Therefore #ship-msg, #pay-msg won't be hidden:
<sytle="text/css"> ... </style>
Your script must be placed after jQuery has been loaded. That is at the end of your document. If you place it before the jQuery script is loaded, the browser won't recognize function calls like $(document).ready() and $("#cForm").validate().
I am assuming that the obvious mistakes (jQuery reference BEFORE the code and style tag mispelling) were simple oversights on your part and that you want to know how to make the appearing/disappearing happen. If you want to make the error appear and then go away after some time, when the validation fails call this function:
function ToggleErrorMessage(messageDiv) {
messageDiv.toggle().delay(20000).toggle();
}
Which will turn the div on, wait 20 secs, and then turn it off. "messageDiv" is the div which you want to apply this to.
This isn't strictly using your validate but this should help you on your way
example

Categories