Radio Button Change Event Doesn't Fire Properly - javascript

It should be fairly simple. I am trying to implement a radio button group. When click on one radiobutton, it will append a text "test" underneath and when click on other radiobutton, the text on the first radiobutton will disappear and the second radiobutton will have the text appended on it. Also, there is a button that add the radiobutton dynamically, and a change event is added into that radiobutton. The following is my code:
The problem with this code is, when I click on the second radiobutton, the first radiobutton text doesn't disappear, and when I check on the third radiobutton, the second and first radiobutton text don't disappear.
How do I fix it?
function add() {
var cat_name = $('input.text').val();
$('div.radioGroup').append('<div><div><input type="radio" name="cat" value="' + cat_name + '"/> ' + cat_name + '<br /></div></div>');
var inputDOM = $('input[value="' + cat_name + '"]');
$('input:radio[name="cat"]').on('change', function() {
// alert(cat_name);
console.log("");
console.log(cat_name);
console.log(cat_name + " ischecked is " + $('input[value="' + cat_name + '"]').is(":checked"));
if ($('input[value="' + cat_name + '"]').is(":checked")) {
inputDOM.parent().after("<span style='margin-left:5em'>test</span><br>");
// alert("yes is working");
} else {
// alert("uncheck is working!");
console.log("uncheck is working");
inputDOM.parent().nextAll().remove();
}
});
$('input.text').val('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="radioGroup">
</div>
<input type="text" name="text" class="text">
<button onclick="add()">Add</button>

Move the
$('input:radio[name="cat"]').on('change', function() {
outside the add() and use delegation:
$('div.radioGroup').on("change",'radio[name="cat"]',function() {
Possibly like this. Too late to guess what you really want
function add() {
var cat_name = $('input.text').val();
$('div.radioGroup').append('<div><div><input type="radio" name="cat" value="' + cat_name + '"/> ' + cat_name + '<br /></div></div>');
$('input.text').val('');
}
$('div.radioGroup').on('change', 'input:radio[name="cat"]',function() {
var cat_name=this.name, inputDOM = $('input[value="' + cat_name + '"]');
console.log("");
console.log(cat_name);
console.log(cat_name + " ischecked is " + $('input[value="' + cat_name + '"]').is(":checked"));
if ($('input[value="' + cat_name + '"]').is(":checked")) {
inputDOM.parent().after("<span style='margin-left:5em'>test</span><br>");
// alert("yes is working");
} else {
// alert("uncheck is working!");
console.log("uncheck is working");
inputDOM.parent().nextAll().remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="radioGroup">
</div>
<input type="text" name="text" class="text">
<button onclick="add()">Add</button>

Related

how to serialize a form under specific conditions

Taka a look at this fiddle here this is a form where a business user enters the offered services.I sent the data with ajax and by serializing the form.
Click edit and add(plus sign) a service...in the example an input is added where it's name attribute value is of this **form= form[5]...**contrast with this with the form of the name attribute value in the other inputs...only the newly added services have the name attribute like this and the reason for that is to serialize only these...and not the others already present in the DOM/stored in the DB.
And now my problem:
Imagine that the user goes to edit the already registered services(or that he goes to edit them and add a new one)...at this case the already registered services wont'be serialized cause of the form the name attribute value has...(and the reason for this is explained above).
What can I do in this case?Sometimes I must serialize only part of a form and sometimes whole of the form.If all the inputs have name attribute value of form[1....] then along with the newly added input...already registered services will be serialized again.
Thanks for listening.
Code follows(you can see it in the fiddle too)
$('.editservices').click(function() {
//console.log(('.wrapper_servp').length);
originals_ser_input_lgth = $('.services').length;
var originals = [];
$('.show_price')
// fetch only those sections that have a sub-element with the .value
class
.filter((i, e) => $('.value', e).length === 1)
// replace content in remaining elements
.replaceWith(function(i) {
var value = $('.value', this).data('value');
var fieldsetCount = $('#serv').length;
var index = fieldsetCount + i;
return '<div class="show_price"><p id="show_p_msg">Price
visibility</p></div>' + '\
<div class="show_p_inpts">' +
'<input class="price_show"' + (value == 1 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="1">yes' +
'<input class="price_show"' + (value == 0 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="0">no' +
'</div>'; // HTML to replace the original content with
});
$('#buttons').removeClass('prfbuttons');
$('#saveserv').addClass('hideb');
$('.actionsserv').removeClass('actionsserv');
priceavail = $(".price_show:input").serializeArray();
});
$('#addser').on('click', function() {
$('#saveserv').css('border','2px solid none');
var serviceCount = $('input.services').length + 1;
var serv_inputs = '<div class="wrapper_servp"><div class="serv_contain">\n\
<input placeholder="service" class="services text" name="form[' + serviceCount + '][service]" type="text" size="40"> \n\
<input placeholder="price" class="price text" name="form[' + serviceCount + '][price]" type="text" size="3"></div>';
var p_show = '<div class="show_p">' +
'<p id="show_p_msg">Price visibility;</p>' +
'<span id="err_show_p"></span><br>' +
'</div>';
var inputs = '<div class="show_p_inpts">' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="1">yes' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="0">no' +
'</div></div>';
$('.wrapper_servp').last().after(serv_inputs + p_show + inputs);
$('#saveserv').removeClass('hideb');
$('#remser').css('display', 'inline');
});
$('#cancelserv').click(function(e) {
e.preventDefault();
//var newinputs = $('.wrapper_servp').length;
//var inp_remv = newinputs - originals_ser_input_lgth;
//$('.wrapper_servp').slice(-inp_remv).remove()
$('.show_p_inpts')
.filter((i, e) => $('.price_show:checked', e).length === 1)
.replaceWith(function(i) {
var value = $('.price_show:checked').attr('value');
return '<span data-value="' + value + '" class="value">' + (value == 1 ? "yes" : "no") + '</span>'
});
});
var groupHasCheckedBox = function() {
return $(this).find('input').filter(function() {
return $(this).prop('checked');
}).length === 0;
},
inputHasValue = function(index) {
return $(this).val() === '';
};
$('#saveserv').click(function(e) {
e.preventDefault();
//from here
var $radioGroups = $('.show_p_inpts');
$('.show_p_inpts').filter(groupHasCheckedBox).closest('div').addClass("error");
$('.services, .price').filter(inputHasValue).addClass("error");
//to here
var $errorInputs = $('input.services').filter((i, e) => !e.value.trim());
if ($errorInputs.length >= 1) {
console.log($errorInputs);
$('#err_message').html('you have to fill in the service'); return;
}
if ($('input.price').filter((i, e) => !e.value.trim()).length >= 1) {
$('#err_message').html('you have to fill in the price'); return;
}
});
var IDs=new Array();
$('body').on('click', '#remser', function(e){
var inputval=$('.services:visible:last').val();
if(inputval!=='')
{r= confirm('Are you sure you want to delete this service?');}
else
{
$('.wrapper_servp:visible:last').remove();
}
switch(r)
{
case true:
IDs.push($('.services:visible:last').data('service'));
$('.wrapper_servp:visible:last').addClass('btypehide');
if($('.serv_contain').length==1)$('#remser').css('display','none');
$('#saveserv').removeClass('hideb').css('border','5px solid red');
//originals.servrem=true;
break;
case false:var i;
for(i=0;i<originals.ser_input_lgth;i++)
{
$('input[name="service'+i+'"]').val(services[i].value);
$('input[name="price'+i+'"]').val(prices[i].value);//εδω set value
}
$('.services').slice(originals.ser_input_lgth).remove();
$('.price').slice(originals.ser_input_lgth).remove();
$('.openservices').addClass('hide').find('.services,.price').prop('readonly', true);
var text='<p class="show_price">Θες να φαίνεται η τιμή;<span data-value="'+ show_pr_val.value +'" class="value">' +(show_pr_val.value==1 ? 'yes':'no') + '</span></p>';
$('.show_p_inpts').remove();
$('.show_price').replaceWith(text);;
break;
}
});
I have an Idea for you. What you can do is when you show the currently existed value in you html instead of giving name attribute just give data-name attribute. I.e
Change this
<input class="services text" data-service="21" size="40" value="hair" type="text" name="service0" readonly="">
To This
<input class="services text" data-service="21" size="40" value="hair" type="text" data-value="hair" data-name="service0" readonly="">
Now when user update this values you can bind an event in jQuery like below.
$(document).ready(function(){
$(".services input").on("change paste keyup", function() {
if($(this).val() === $(this).attr("data-value"))
{
$(this).removeAttr("name");
}else{
$(this).attr("name",$(this).attr("data-name"));
}
});
});
By this way you can give name attribute to only those elements whose values are changed. Now each time you can serialize the whole form and it will only get the value of changed elements.
Don't forget to give unique class to already existed elements so you can bind on change event. Hope its clear to you.

How to disable value in select option when it already selected by another select option

So, i have a simple form like this:
<div class="form-group">
<label class="">No Inventaris</label>
<div id="container">
<input type="button" name="noInv" class="form-control" id="add_field" value="Klik untuk membuat text field baru"><br>
<script type="text/javascript">
var count = 0;
$(function(){
$('#add_field').click(function(){
count += 1;
$('#container').append(
'<strong >No Inv Barang Ke ' + count + '</strong><br />'
+ '<select id="field_' + count + '" name="fields[]' + '" class="form-control no_inv"><?php $noInv = $this->modelku->select_inv() ?> <?php foreach($noInv->result() as $inv){ ?> <option value="<?php echo $inv->no_inv ?>"><?php echo $inv->no_inv ?></option><?php } ?></select><br>' );
});
});
</script>
</div>
When i click the button the field will regenerate select option, and the value is from database
select_inv function:
public function select_inv()
{
$this->db->select("no_inv");
$this->db->from('detail_barang');
$this->db->where("kondisi = 'Ada' ");
$query = $this->db->get();
return $query;
}
My Question: How can i disable value in select option when it already selected by another select option?
Try this if this is what you need.
i just created a sample dropdown and in my jquery i trigger the event change using the class of all select option then i will get the value of the select and id. after getting the value i check the val if it is empty or not if not empty then i will use the each function for all the select and get their id attribute so i can compare it with the id of the select and if their id is not the same then i will disabled the option with the same value of the selected dropdown.
and i use focus event for getting the previous value so i can reset whether the user change the value of the selected option.
$( document ).ready(function() {
$('body').on('click','#add_field',function(){
count += 1;
$('#container').append(
'<strong >No Inv Barang Ke ' + count + '</strong><br />'
+ '<select id="field_' + count + '" name="fields[]' + '" class="form-control no_inv select_alternate"> <option value="">select</option><option value="test1">test1</option><option value="test2">test2</option><option value="test3">test3</option></select><br></select><br>' );
});
var count =0;
var previous;
var selectedData = [];
$('body').on('click','.select_alternate',function(){
previous = this.value;
});
$('body').on('change','.select_alternate',function(){
var val = this.value;
var id = $(this).attr('id');
if(val != ''){
$(".select_alternate").each(function(){
var newID = $(this).attr('id');
if(id != newID){
$('#'+newID).children('option[value="' + val + '"]').prop('disabled',true);
$('#'+newID).children('option[value="' + previous + '"]').prop('disabled',false);
selectedData.splice($.inArray(val, selectedData),1);
}else{
selectedData.push(val);
}
});
}else{
$(".select_alternate").each(function(){
var newID = $(this).attr('id');
if(id != newID){
$('#'+newID).children('option[value="' + previous + '"]').prop('disabled',false);
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="">No Inventaris</label>
<div id="container">
<input type="button" name="noInv" class="form-control" id="add_field" value="Klik untuk membuat text field baru"><br>
</div>

Form won't submit after user checks a radio button and checkbox

I have a form with three radio buttons and a checkbox set up. A user must click one radio button and click the checkbox to submit. I am using WP-Polls which is a plugin for WordPress. For some reason, the form won't submit. I click a radio button, click the checkbox, but hitting submit does nothing. The live site can be seen here. The relevant section is the dark voting section on top.
HTML
<form id="polls_form_1" class="wp-polls-form" action="/index.php" method="post">
<p style="display: none;"><input type="hidden" id="poll_1_nonce" name="wp-polls-nonce" value="12a6404147"></p>
<p style="display: none;"><input type="hidden" name="poll_id" value="1"></p>
<div id="polls-1-ans">
<ul>
<li><input type="radio" id="poll-answer-1" name="poll_1" value="1"></li>
<li><input type="radio" id="poll-answer-2" name="poll_1" value="2"></li>
<li><input type="radio" id="poll-answer-3" name="poll_1" value="3"></li>
</ul>
<label class="check-terms"><input type="checkbox">I am over 18 and I have read and understand the Terms of Use</label>
<input type="submit" name="vote" value="Vote" class="Buttons" />
</form>
JavaScript
$(function() {
window.poll_vote = function(num) {
console.log(num);
}
$('.wp-polls-form').submit(function(e) {
if (!$('input:radio', this).is(':checked')) {
alert('Please pick a beat.');
return false;
}
if (!$('input:checkbox', this).is(':checked')) {
alert('Please agree to the Terms of Use.');
return false;
}
poll_vote(1);
return false;
});
});
Here is the function for poll_vote(1):
// When User Vote For Poll
function poll_vote(current_poll_id) {
jQuery(document).ready(function($) {
if(!is_being_voted) {
set_is_being_voted(true);
poll_id = current_poll_id;
poll_answer_id = '';
poll_multiple_ans = 0;
poll_multiple_ans_count = 0;
if($('#poll_multiple_ans_' + poll_id).length) {
poll_multiple_ans = parseInt($('#poll_multiple_ans_' + poll_id).val());
}
$('#polls_form_' + poll_id + ' input:checkbox, #polls_form_' + poll_id + ' input:radio, #polls_form_' + poll_id + ' option').each(function(i){
if ($(this).is(':checked') || $(this).is(':selected')) {
if(poll_multiple_ans > 0) {
poll_answer_id = $(this).val() + ',' + poll_answer_id;
poll_multiple_ans_count++;
} else {
poll_answer_id = parseInt($(this).val());
}
}
});
if(poll_multiple_ans > 0) {
if(poll_multiple_ans_count > 0 && poll_multiple_ans_count <= poll_multiple_ans) {
poll_answer_id = poll_answer_id.substring(0, (poll_answer_id.length-1));
poll_process();
} else if(poll_multiple_ans_count == 0) {
set_is_being_voted(false);
alert(pollsL10n.text_valid);
} else {
set_is_being_voted(false);
alert(pollsL10n.text_multiple + ' ' + poll_multiple_ans);
}
} else {
if(poll_answer_id > 0) {
poll_process();
} else {
set_is_being_voted(false);
alert(pollsL10n.text_valid);
}
}
} else {
alert(pollsL10n.text_wait);
}
});
}
The problem is the new checkbox(terms & conditions) that is added inside the form.
If you can change the poll_vote function...
Change
<label class="check-terms"><input type="checkbox">
to
<label class="check-terms"><input type="checkbox" class="check-terms">
then
a("#polls_form_" + poll_id + " input:checkbox, #polls_form_" + poll_id + " input:radio, #polls_form_" + poll_id + " option")
to
a("#polls_form_" + poll_id + " input:checkbox, #polls_form_" + poll_id + " input:radio, #polls_form_" + poll_id + " option").not('.check-terms')

How to do client side validations if some text boxes are generated dynamically

I'm working on a form which has this add button, if the button is clicked a text box is foing to generate and i have a minus button to cancel it.
my problem is i have to work on client side validations in this page
the code i used to generate new text boxes is
i = 0;
var counter = 2;
$("#addButton").click(function () {
optionCount++;
i++;
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv'+i);
newTextBoxDiv.after().html('<label>Option : </label>' +
'<input type="text" class="add_input" name="textbox' + counter + '" id="textbox' + counter + '" > <input type="button" class="rem_img minusclick" id="removeButton'+i+'" alt="Remove" title="Remove" onclick="RemoveButton(\''+i+'\',\''+counter+'\')">');
newTextBoxDiv.appendTo("#TextBoxesGroup");
optionIds.push(counter);
counter++;
The validation is to be done after clicking the submit button. and i need to display an error message beside each empty text box(that is generated by clicking add button)
im confused where to start and what exactly i have to do for this
Please help..
I add onchange method textbox;
i = 0;
var counter = 2;
$("#addButton").click(function () {
optionCount++;
i++;
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv'+i);
newTextBoxDiv.after().html('<label>Option : </label>' +
'<input type="text" onchange="Validate(this,\"ValueControl\")" class="add_input" name="textbox' + counter + '" id="textbox' + counter + '" > <input type="button" class="rem_img minusclick" id="removeButton'+i+'" alt="Remove" title="Remove" onclick="RemoveButton(\''+i+'\',\''+counter+'\')">');
newTextBoxDiv.appendTo("#TextBoxesGroup");
optionIds.push(counter);
counter++;
Create This function;
function Validate(elementObject,validType){
if(validType=="ValueControl"){
if($(elementObject).val()==''){
$(elementObject).css("background-color","#000000");
}
}
}

How to only clear file upload field?

Here is the JSfiddle: http://jsfiddle.net/buyC9/128/
I want to clear only the file upload field when pressed on clear.
My HTML:
<h1>Upload image:</h1>
<input type="file" name="blog[opload]" id="blog_opload" class="imagec">
<input type="url" size="50" name="blog[url]" id="blog_url" class="imagec">
<div id="preview">
</div>
My Jquery:
$('input').change(function() {
var el = $(this);
if (this.value === "") {
$('.imagec').prop('disabled', false);
this.disabled = false;
$('#preview').hide();
} else {
$('.imagec').prop('disabled', true);
el.prop('disabled', false);
alert(el.val());
if (el.attr('type') == 'url') {
$('#preview').show().html('<img src=' + '"' + el.val() + '"' + ' />');
}
}
});
function reset_html(id) {
$('.' + id).html( $('.' + id).html() );
}
var imagec_index = 0;
$('input[type=file]').each(function() {
imagec_index++;
$(this).wrap('<div id="imagec_' + imagec_index + '"></div>');
$(this).after('<input type="button" value="Clear" onclick="reset_html(\'imagec_' + imagec_index + '\')" />');
});
How about:
$('input[value="Clear"]').click(function(){
$('#blog_opload').val('');
});
Example: jsFiddle
You could also get rid of onclick="reset_html(\'imagec_' + imagec_index + '\')" if you use this.
Quick answer is replace it:
$("#clear").click(function(event){
event.preventDefault();
$("#control").replaceWith("<input type='file' id='control' />");
});
<input type="file" id="control" />
Clear
You can do simply
$("#filuploadId")[0].value = "";
In your code you meant to use the ID selector but instead are using class selector.
$('.' + id).html( $('.' + id).html() );
should be
$('#' + id).html( $('#' + id).html() );
Updated jsFiddle

Categories

Resources