JQuery remove element from parent - javascript

I have a "Try Again!" message that appears when the inserted value exists in my dropdown select list, this is my code:
//I am trying to remove this message once the user starts typing again:
$('#new_day').on('input', function(){
//Get input value
var input_value = $(this).val();
//Remove disabled from the button
$('#new_day_save').removeAttr('disabled');
//iterate through the options
$(".days > option").each(function() {
//If the input value match option text the disable button
if( input_value == $(this).text()){
$('#new_day_save').attr('disabled', 'disabled');
$('#new_day_save').parent().append("<p id=\"error_message\" style=\"color: red\">Try again !</p>");
}else{
$('#new_day_save').parent().remove("#error_message");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="days">
<option>Monday</option>
<option>Friday</option>
</select>
<p>You have another proposition? Add it to the list.</p>
<div>
<input id="new_day" type="text" />
</div>
<input id="new_day_save" type="button" value="save new day"/>

you can just remove the #error_message by adding this to your event handler just before you compare input value to option
$('#new_day_save').parent().find('#error_message').remove()
and you can remove the else condition.
$('#new_day').on('input', function(){
//Get input value
var input_value = $(this).val();
//Remove disabled from the button
$('#new_day_save').removeAttr('disabled');
$('#new_day_save').parent().find('#error_message').remove();
//iterate through the options
$(".days > option").each(function() {
//If the input value match option text the disable button
if( input_value == $(this).text()){
$('#new_day_save').attr('disabled', 'disabled');
$('#new_day_save').parent().append("<p id=\"error_message\" style=\"color: red\">Try again !</p>");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="days">
<option>Monday</option>
<option>Friday</option>
</select>
<p>You have another proposition? Add it to the list.</p>
<div>
<input id="new_day" type="text" />
</div>
<input id="new_day_save" type="button" value="save new day"/>

This line $('#new_day_save').parent().remove("#error_message"); will remove parent element.
To remove specific element in jQuery, do simply since it's a id selector which is unique element,
$("#error_message").remove();

Related

Perform operations on a cloned form

I have created a form that contains two drop-down lists, when the user selects an item from the first list, the data for the second is automatically updated. I use jquery to do this and it works perfectly except that when I duplicate the form, the drop-down list N ° 1 of the duplicated form no longer updates the drop-down list N ° 2 so I would like to know how can I perform the same action on a cloned form (update a drop-down list by selecting one entered in another) and save the entries of all the cloned forms in a database.
Cordially!
here is the code i use
<form id="myForm">
<div id="clonedSection1" class="clonedSection">
<select class="form-control" name="productName[]" id="productName" >
<option value="0" selected>Selectionner le produit</option>
<option value="copy">Copie</option>
<option value="scan">Scan</option>
</select>
<select class="form-control" name="productPrice[]" id="quant" disabled>
<option value="pu" selected>P.U</option>
</select>
</div>
<div>
<input type="button" id="btnAdd" value="add another name" />
<input type="button" id="btnDel" value="remove name" />
</div>
<!-- script that allows you to modify the data in a drop-down list when an item is selected in another-->
<script type="text/javascript">
$("#productName").change(function () {
var val = $(this).val();
if (val == "copy") {
$("#quant").html("<option value='25'> 25$ </option>");
} else if (val == "scan") {
$("#quant").html("<option value='50'> 10$ </option>");
}
});
</script>
<!-- script that clones the form-->
<script type="text/javascript">
$(document).ready(function() {
$("#btnAdd").click(function() {
var num = $(".clonedSection").length;
var newNum = new Number(num + 1);
var newSection = $("#clonedSection" + num).clone().attr("id", "clonedSection" + newNum);
newSection.children(":nth-child(5)").children(":first").attr("id", "productName" + newNum).attr("name", "productName[]" + newNum);
newSection.children(":nth-child(6)").children(":first").attr("id", "quant" + newNum).attr("name", "productPrice[]" + newNum);
$(".clonedSection").last().append(newSection)
$("#btnDel").attr("disabled","");
});
$("#btnDel").click(function() {
var num = $(".clonedSection").length; // how many "duplicatable" input fields we currently have
$("#clonedSection" + num).remove(); // remove the last element
// enable the "add" button
$("#btnAdd").attr("disabled","");
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$("#btnDel").attr("disabled","disabled");
});
$("#btnDel").attr("disabled","disabled");
});
</script>
I have written simple and clean code.
Follow below steps:
Don't use ID so you need to use class name instead of id because of ID should be unique.
If appending dynamically element then need to use .on() instead of .change() method.
.cloned-section section should be separate from Add Button.
Each time pick clone element by .cloned-section>div:nth-child(1) this nth-child method.
Set value in input field by onchange .product-name class.
Remove element by onclick .btn-remove class.
When append clone element by append() method then select+input values need to set null so you can see in my jQuesy code and also see commented text.
I hope below snippet will help you lot.
$(document).on('click', '#btnAdd', function(){
// Make clone by clone() method and append REMOVE button for remove section
var cloneElement = $('.cloned-section>div:nth-child(1)').clone();
cloneElement.append('<button type="button" class="btn btn-danger btn-remove"><span aria-hidden="true">×</span></button>');
// Select value set Zero (0)
cloneElement.find('select').val(0);
// Input value set empty
cloneElement.find('input').val('');
$('.cloned-section').append(cloneElement);
});
// On change product name then set price on price field
$(document).on('change', '.product-name', function(){
var getValue = $(this).val();
$(this).parent().find('.product-price').val(getValue+'%');
});
// Click on Remove button and delete product/price section
$(document).on('click', '.btn-remove', function(){
$(this).parent().remove();
});
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<div class="container my-2">
<div class="row">
<div class="col-sm-12">
<form class="form-inline" id="myForm">
<div class="cloned-section w-100">
<div class="w-100 mt-2">
<select class="form-control w-50 product-name" name="productName[]">
<option value="0" selected>Select Product</option>
<option value="25">Copy</option>
<option value="50">Scan</option>
<option value="75">Paste</option>
<option value="100">Cut</option>
</select>
<input class="form-control w-25 product-price text-center" name="productPrice[]" readonly>
</div>
</div>
<div class="w-100 mt-2">
<button type="button" id="btnAdd" class="btn btn-success">Add Another Name</button>
</div>
</form>
</div>
</div>
</div>
There are some minor problems of your code:
Use classname instead of id for DOM elements that going to be cloned.
It is because id is unique. Different elements should not share the
same id. If you clone an element with id, there would be elements
sharing the same id.
Use .on() instead of .change() for elements that generate
dynamically.
I'm not sure if you really want to insert a new "clonedSection"
inside the last "clonedSection". If you are not going to do this and
would like to insert new "clonedSection" right after the last
"clonedSection", use
newSection.insertAfter($(".clonedSection").last());
value of .attr("disabled", <>) should be either true or false, but not "" and disabled
$(document).ready(function() {
//use on() instead of change() for elements that generate dynamically
$("body").on("change", ".productName", function() {
var _this = $(this);
var quant = _this.closest(".clonedSection").find(".quant");
var val = _this.val();
if (val == "copy") {
quant.html("<option value='25'> 25$ </option>");
} else if (val == "scan") {
quant.html("<option value='50'> 10$ </option>");
}
});
$("#btnAdd").click(function() {
var num = $(".clonedSection").length;
var newNum = num + 1;
var newSection = $("#clonedSection" + num).clone().attr("id", "clonedSection" + newNum);
newSection.children(":nth-child(5)").children(":first").attr("id", "productName" + newNum).attr("name", "productName[]" + newNum);
newSection.children(":nth-child(6)").children(":first").attr("id", "quant" + newNum).attr("name", "productPrice[]" + newNum);
newSection.insertAfter($(".clonedSection").last()); //insert right after the last clonedsection
$("#btnDel").attr("disabled", false); //disabled should be either true/false but not ""
});
$("#btnDel").click(function() {
var num = $(".clonedSection").length;
$("#clonedSection" + num).remove();
$("#btnAdd").attr("disabled", false);
if (num - 1 == 1)
$("#btnDel").attr("disabled", true);
});
$("#btnDel").attr("disabled", true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<!--If you are going to clone DOM element, please use classname instead of id-->
<div id="clonedSection1" class="clonedSection">
<select class="form-control productName" name="productName[]">
<option value="0" selected>Selectionner le produit</option>
<option value="copy">Copie</option>
<option value="scan">Scan</option>
</select>
<select class="form-control quant" name="productPrice[]">
<option value="pu" selected>P.U</option>
</select>
</div>
<div>
<input type="button" id="btnAdd" value="add another name" />
<input type="button" id="btnDel" value="remove name" />
</div>
Hope this help :D

How to select all element with specific value and update the value using jquery

I want to select all input elements with a specific value that the user enters on runtime in the input field and update the value on click of a button here is what I tried to accomplish this.
<input type="text" class="test" >
<button>
check value
</button>
var button = $("button")
button.on("click", function(){
$("input[value='10']").val("100");
})
But its not working here is link to the jsfiddle.
What you're looking for is .each()
button.on("click", function(){
$("input").each(function() {
if($(this).val() == "10") {
$(this).val("100");
}
});
});
This loops through all inputs and sets the value to 100 of those with value 10
the "[value='myValue']" selector refers only to the initial attribute value of the input
$("input[value='10']") is a attribute selector. Putting some value does not set the value attribute.
To make that work you can set the attribute with attr() explicitly:
var button = $("button");
$("input[type=text]").on('input', function(){
$(this).attr('value', $(this).val());
});
button.on("click", function(){
$("input[value='10']").val('100');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="test">
<input type="text" class="test">
<button>
check value
</button>
You are selecting all inputs with the current value of 10, but your input doesn't have a current value. Set it to 10 and it should work:
<input value="10" type="text" class="test" >

Jquery removing dynamic drop down removes entire parent div

I am trying to add drop down on click of button.
From the 2nd drop down on wards, there is a remove button , which basically will remove the drop down.
The problem is when i click the remove link, the entire div is getting removed, even the 1st drop down.
I want only that corresponding drop down to be deleted .
<div class="row myccccccbackground" style="padding: 5px;margin: 265px 0 6px;"><span class="content_shorting"> <?php echo $this->translate('Call for action button 1');?><img class="Text_Action_bt1_tooltip" data-toggle="tooltip" data-placement="right" style="margin: 0px 0px -7px 3px;" src="<?=$this->basePath()?>/images/info_icon_grey.png"></span><br/><br/>
<br>
<button type='button' id = "btnAdd" style="position: relative;bottom: 24px;" >Add another...</button><br/><br/>
<div class="fields_action"><br>
<select id="action" class="increment" style="position: relative;bottom: 32px;">
<option value="N">Select Action</option>
<option value="Y">SMS</option>
<option value="Y">Call</option>
<option value="Y">Call Back</option>
<option value="Y">Email</option>
<option value="Y">Website </option>
</select><br/>
<span style="color:red;" class="key-error-class" id="key_error_1" ></span>
<span id="valueResponse_1" class="valueResponse-class"></span>
</div>
</div>
JS:
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".fields_action"); //Fields wrapper
var add_button = $("#btnAdd"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
var actionid = $('#action');
//UPDATED
if (actionid.val() === '' || actionid.val() === 'N') {
alert("Please select an item from the list and then proceed!");
$('#action').focus();
return false;
}
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><select id="action" class="increment"><option value="N">Select Action</option><option value="Y">Call</option><option value="Y">Call Back</option><option value="Y">Email</option><option value="Y">Website </option></select> <input name="TextAdPriority" class="adtitle nospaceallow integeronly" value="" type="text">Remove<br/></div>');
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
UPDATE: The above validation check - ie) if default option is selected then the alert is thrown only for 1st drop down.
How to check for default value from the 2nd drop down.
You missed to add <div> at the begining of append method.
Here is complete code.
$(wrapper).append('<div><select id="action" class="increment"><option value="N">Select Action</option><option value="Y">Call</option><option value="Y">Call Back</option><option value="Y">Email</option><option value="Y">Website </option></select> <input name="TextAdPriority" class="adtitle nospaceallow integeronly" value="" type="text">Remove<br/></div>');
To validate multiple dropdowns you can modify your code following way. It is working fine for me.
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
//UPDATED
var dropdowns = $('.increment');
var isValid = true
dropdowns.map(function(idx, dropdown) {
if (dropdown.value === '' || dropdown.value === 'N') {
alert(`Please select an item on position ${idx+1} dropdown and then proceed!`);
$(dropdown).focus();
isValid = false;
}
})
if(isValid && x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><select id="action" class="increment"><option value="N">Select Action</option><option value="Y">Call</option><option value="Y">Call Back</option><option value="Y">Email</option><option value="Y">Website </option></select> <input name="TextAdPriority" class="adtitle nospaceallow integeronly" value="" type="text">Remove<br/></div>');
}
});

Using JS prepend for a div, rather than hiding

I have some existing code with a select box, where I'm looking at the option value and matching it to the value of a hidden input for divs within a foreach loop. I got it working the way I want (where, depending on the selection, if the value of the hidden input is '0' it would hide that div). Again, the show/hide works perfectly.
However, I now need to get it working so that if the value is '1' it would prepend those affected divs or show them first. I've never used prepend or append before and I can't get this working for some reason. I tried using the value '0' with append but it just hid everything. I think prepend would be better.
Here's the previous Working 'hide' javascript:
<script type="text/javascript">
$(function(){
$('#filterText').on('change', function() {
var currentVal = $(this).val();
console.log(currentVal)
$(".group-container").show();
if (currentVal == 'popularity') {
$('.group-container input[name="topseller"]').each(function (index, value){
if($(this).val() == "0"){
$(this).parent('.group-container').hide();
//console.log(currentVal)
}
});
} else if (currentVal == 'recently_ordered') {
$('.group-container input[name="reorder"]').each(function (index, value){
if($(this).val() == "0"){
$(this).parent('.group-container').hide();
// console.log(currentVal)
}
});
}
});
});
</script>
Here's the HTML
<div>
<span style="color:#fff;"><strong>Sort by:</strong></span>
<select id="filterText" class="uk-text-muted" style="margin-top:10px; width:33%; height:30px; font-size: 16px;" >
<option id="allitems" class="uk-text-muted" style="font-size: 16px;" selected data-default value="" selected data-default>All Items</option>
file
<option id="recent" class="uk-text-muted" style="font-size: 16px;" value="recently_ordered">Recently Ordered </option>
</select>
</div>
#foreach ($orderFormData->pgroups as $pgroup)
<div class="group-container">
<!-- <input type='hidden' name='search' value='{{ x.search }}' > -->
<input type="hidden" name="topseller" value="{{$pgroup->topseller}}" />
<input type="hidden" name="reorder" value="{{$pgroup->reorder}}"/>
//rest of the content here
And the new JS I'm attempting, but has no action:
<script type="text/javascript">
$(function(){
$('#filterText').on('change', function() {
var currentVal = $(this).val();
console.log(currentVal)
$(".group-container").show();
if (currentVal == 'recently_ordered') {
$('.group-container input[name="reorder"]').each(function (index, value)
{
if($(this).val() == "1"){
$(this).prepend('.group-container')
}
});
}
});
});
</script>
$(this).prepend('.group-container')
This piece of code is going to just prepend the text ".group-container" within the selected element. So you would get
<input ....>.group-container</input>
If you instead did this:
$(this).prepend('<div class="group-container">);
You would get it added to the beginning of your existing element:
<input....><div class="group-container"></div></input>
I think what you want is "wrap":
$(this).wrap('<div class="group-container">');
Which should yield
<div class="group-container"><input.../></div>
http://api.jquery.com/wrap/

How to open a div selecting a value from dropdown in jQuery

I need an application where i have a drop down where i have some values and and my requirement is that when i click any value on that drop down a div will open.I have implemented that but my code is not properly working.Here what i have done so far.
<div class="form-control">
<label class="lebelMergin" for="branch_branchTypeId">
<span class="spanMergin">Office Type<span class="required">*</span></span>
<s:select name="branch.branchTypeId" id="branch_branchTypeId" requiredLabel="true" list="%{dataArr['branchTypeList']}" listValue="name"
listKey="id" headerKey="" headerValue="Select Type" >
</s:select>
</label>
</div>
<div style='display:none;' id='business'>Business Name
<br/>
<br/>
<input type='text' class='text' name='business' value size='20' />
<br/>
</div>
<style>
#business {
display:none;
}
</style>
<script>
(function() {
$('#branch_branchTypeId').on('change', function () {
$("#business").css('display', (this.value == '1') ? 'block' : 'none');
});
But when i clicking on that values in the drop down only for one value the input box is coming but i want the functionality for all the value.Here i am attaching the screen ...For HO the input box is coming but for others it is not.
Which "option" tags do yo have in your select (dropdown)?
May be this would be help:
$('#branch_branchTypeId').on('change', function (event) {
var vl = $(this).val();
var target = $("#business");
if (vl) {
target.show();
} else {
target.hide();
}
});
The problem lies in your test this.value == 1. You can use this.selectedIndex instead.
$('#branch_branchTypeId').on('change', function () {
$("#business").css('display', (this.selectedIndex >= 1) ? 'block' : 'none');
});
Following your comment, I assumed that selectIndex == 0 corresponds to the default option, with business div not displayed.
See Fiddle: http://jsfiddle.net/3nvdeoab/

Categories