Different behavoir after clicking button jQuery - javascript

Im here again... Jquery noob. So I have this form that works with jQuery. The problem is that it has a different behaviour after clicking "Add".
https://jsfiddle.net/h4exrmdz/6/
Just try this to understand quickly:
Select "Other" in the first select. You can see that a new form appears.
Select "Option 1" now. You can see the form disappears.
Click "Add".
Select "Other" again in the first select. The new form doesnt appear anymore, even if you click "Remove". (It should work like before).
HTML
<table>
<th>
<p>Select <select autocomplete="off" name="custom_material_floor" id="custom_material_floor">
<option value="1" selected="selected">Option1</option>
<option value="2">Option2</option>
<option value="3">Option3</option>
<option value="Other">Other</option>
</select>
<div id="custom_material_floorValue">
Custom:
<form name="custom_material_floorValue" id="custom_material_floorValue">
<input type="text" size="4">
<input type="text" size="4">
<input type="text" size="4">
<input type="text" size="4">
<input type="text" size="4">
<input type="text" size="4">
</form>
</div>
</th>
<th>
<div class="input_fields_wrap">
<button class="add_field_button">Add</button>
</div>
</th>
</table>
Script jQuery
$(document).ready(function()
{$("#custom_material_floor").change(function()
{if($(this).val() == "Other")
{$("#custom_material_floorValue").show();}
else
{$("#custom_material_floorValue").hide();}});
$("#custom_material_floorValue").hide();
});
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div></p>Name<input name="nombre" type="text" onkeyup="update()" maxlength="16" />\
Select <select name="username">\
<option value="1">Option1</option>\
<option value="2">Option2</option>\
<option value="3">Option3</option>\
<option value="4">Other</option>\
</select><form class="custom_material" id="custom_material" style="display:none">\
<input type="text" size="4">\
<input type="text" size="4">\
<input type="text" size="4">\
<input type="text" size="4">\
<input type="text" size="4">\
<input type="text" size="4"></form>\
Remove</div>'); //add form
$("select").off("change");
$("select").on("change", function(e){
var selEl = $(e.currentTarget);
var inputSel = "form.custom_material";
if (e.currentTarget.value == 4) {
selEl.parent().find(inputSel).show();
} else {
selEl.parent().find(inputSel).hide();
}
});
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
$(document).ready(function() {update();});
})
});
I suppose its easy but I dont know whats happening. Any idea?

If you see the code, you have a second onChange event at the lower part that fires for all the select controls that you have. Onload, it triggers the First onChange event, but after Add, the event triggered is now the second onChange event.
First onChange event:
$("#custom_material_floor").change(function() {
if ($(this).val() == "Other") {
$("#custom_material_floorValue").show();
} else {
$("#custom_material_floorValue").hide();
}
});
Second onChange event:
$("select").on("change", function(e) {
var selEl = $(e.currentTarget);
var inputSel = "form.custom_material";
if (e.currentTarget.value == 4) {
//alert("other clicked");
selEl.parent().find(inputSel).show();
} else {
//alert("option clicked");
selEl.parent().find(inputSel).hide();
}
});

Here is the code working properly if any interested:
https://jsfiddle.net/h4exrmdz/10/
Script jQuery
$(document).ready(function()
{$("#custom_material_floor").change(function()
{if($(this).val() == "Other")
{$("#custom_material_floorValue").show();}
else
{$("#custom_material_floorValue").hide();}});
$("#custom_material_floorValue").hide();
});
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div></p>Name<input name="nombre" type="text" onkeyup="update()" maxlength="16" />\
Select <select class="additional_custom" name="username">\
<option value="1">Option1</option>\
<option value="2">Option2</option>\
<option value="3">Option3</option>\
<option value="4">Other</option>\
</select><form class="custom_material" id="custom_material" style="display:none">\
<input type="text" size="4">\
<input type="text" size="4">\
<input type="text" size="4">\
<input type="text" size="4">\
<input type="text" size="4">\
<input type="text" size="4"></form>\
Remove</div>'); //add form
$(".additional_custom").off("change");
$(".additional_custom").on("change", function(e){
var selEl = $(e.currentTarget);
var inputSel = "form.custom_material";
if (e.currentTarget.value == 4) {
//alert("other clicked");
selEl.parent().find(inputSel).show();
} else {
//alert("option clicked");
selEl.parent().find(inputSel).hide();
}
});
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
$(document).ready(function() {update();});
})
});

Related

How to get Select Option working with disable and enable submit button

I have a form with textarea, input type: text, radio and checkbox. Also it has select option and disable submit button at first.
An idea is if all fields are filled in then the submit button will be enable.
Everything is working as expected, but it seems like my code ignores select option. That means the submit button is enable before I do select option.
Below is my code for select option:
var pickOne = $('#pickone option:selected').length === 0;
if (pickOne) {
console.log("pickOne: " + pickOne);
filled = false;
}
I wonder if I miss something. Please take a look at my sample in jsfiddle
HTML
<form action="" method="post" id="subnewtopicform" />Title:
<input type="text" name="title"> <br />
Name:
<input type="text" name="name">
<br/>Description:
<textarea name="description"></textarea>
<br/>Category:
<ul class="list:category categorychecklist form-no-clear" id="categorychecklist">
<li id="category-19">
<label class="selectit">
<input type="radio" id="in-category-19" name="category" value="19">Animation</label>
</li>
<li id="category-20">
<label class="selectit">
<input type="radio" id="in-category-20" name="category" value="20">Anime</label>
</li>
</ul>
<div class="fieldText" id="multi-select">
<lable>
<input class="item" name="item1" type="checkbox">Item 1
</lable>
<lable>
<input class="item" name="item2" type="checkbox">Item 2
</lable>
</div>
<p>
<select name="pickone" id= "pickone" required>
<option selected="selected" value="">Select one</option>
<option value="a">aktif</option>
<option value="l">terkunci</option>
<option value="b">blokir</option>
</select>
</p>
<input type="submit" value="Submit Topic" class="button-primary" name="subnewtopic" id="subnewtopic" disabled="disabled" />
</form>
JS
//function check() {
$('#subnewtopicform').on("keyup change", function() {
var inputs = $("input");
var textareas = $("textarea");
var filled = true;
var oneChecked = false;
var multiChecked = false;
//var pickOne = $('#pickone option:selected').length === 0;
//var pickOne = false;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type === "text" && !inputs[i].value) {
filled = false;
}
if (inputs[i].type === "radio" && inputs[i].checked) {
oneChecked = true;
}
if (inputs[i].type === "checkbox" && inputs[i].checked) {
multiChecked = true;
}
}
if (!oneChecked) {
filled = false;
}
if (!multiChecked) {
filled = false;
}
var pickOne = $('#pickone option:selected').length === 0;
if (pickOne) {
console.log("pickOne: " + pickOne);
filled = false;
}
for (var j = 0; j < textareas.length; j++) {
if (!textareas[j].value) {
filled = false;
}
}
if (filled) {
$("#subnewtopic").removeAttr('disabled');
} else {
$("#subnewtopic").prop('disabled', 'disabled');
}
}
)
/* window.addEventListener("keyup", check);
window.addEventListener("click", check); */
but it seems like my code ignores select option
No. Your code is not ignoring the select option.
<select name="pickone" id= "pickone" required>
<option selected="selected" value="">Select one</option> //This is selected by default
<option value="a">aktif</option>
<option value="l">terkunci</option>
<option value="b">blokir</option>
</select>
"Select one" is a valid option and is selected by default, so this code:
$('#pickone option:selected').length
Will return 1 even if "Select one" is the selected option.
In my opinion the best thing you can do is validate the select by it's value being !== '' considering that's the value of "Select one" option which are your "invalid" option.

html Unlimited hierarchy input to form

I want to add form for adding new categories. Categories might have infinitive sub categories.
$(document).ready(function () {
var max_fields = 15; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="input_fields_wrap_sec"><input type="text" name="mytext[]" placeholder="Sub-Category title"/>\n\
<input type="submit" name="submit1" value="Add Sub-Sub-Category" class="add_field_button" >\n\
Remove</div>'
); //add input box
}
});
$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="POST">
<div class="input_fields_wrap">
<p>Please enter the Category Title</p>
<input type="text" name="mytext[]" placeholder="Category title">
<input type="submit" name="submit1" value="Add Sub-Category" class="add_field_button" >
</div>
<input type="submit" name="submit" value="submit">
</form>
Now I have form like this and when I press "add sub-sub category" it should appear new "sub-sub category" input with buttons: "add sub-sub-sub category" and "remove"
It should be like this, the deep of categories is infinitive
Labas!
You could try something like this:
function getValueText(level) {
let i = 0
let text = "Add ";
while (i < level) {
text += "sub-"
i++;
}
return text + "category";
}
function appendInnerCategory(level, element) {
var myDiv = document.createElement("div");
myDiv.className = "level-" + level
var btn = document.createElement("input");
btn.type = "button";
btn.value = getValueText(level);
btn.addEventListener("click", function(event) {
appendInnerCategory(level + 1, event.target.parentNode);
});
var textBox = document.createElement("input");
textBox.type = "text";
myDiv.appendChild(textBox);
myDiv.appendChild(btn);
element.appendChild(myDiv);
}
appendInnerCategory(0, document.querySelector('.wrapper'));
HTML:
<div class="wrapper"></div>
Fiddle: http://jsfiddle.net/7L382gow/
Updated fiddle to maintain a structure object, while manipulating the DOM.
Submit will print the resulting hierarchy to console.
http://jsfiddle.net/bqk6pmjg/

getting values to populate a text instead of the span

I have pieced together a script that adds the values in text boxes and displays the sums in a span. I have tried a ton of things, but I can not get it to display the sums in a input textbox. Here is a fiddle that I have been working in ..
http://jsfiddle.net/elevationprint/MaK2k/17/
Basically I want to change the spans to input text boxes. If anyone can take a look and let me know what I am missing, I would appreciate it!
The code is this
HTML
Red<br>
12x12<input class="qty12" value="" /><br/>
12x24<input class="qty24" value="" /><br>
<br>
Blue<br>
12x12<input class="qty12" value="" /><br/>
12x24<input class="qty24" value="" /><br>
<br><br>
Total = <span class="qty12lable"></span> x $.95<br>
Total = <span class="qty24lable"></span> x $1.40<br>
SCRIPT
$('.qty12').keyup(function(){
var qty12Sum=0;
$('.qty12').each(function(){
if (this.value != "")
qty12Sum+=parseInt(this.value);
});
// alert('foo');
$(".qty12lable").text(qty12Sum);
//console.log(amountSum); });
$('.qty24').keyup(function(){
var qty24Sum=0;
$('.qty24').each(function(){
if (this.value != "")
qty24Sum+=parseInt(this.value);
});
// alert('foo');
$(".qty24lable").text(qty24Sum);
//console.log(amountSum); });
You can target the input fields like so:
Total = <input class="qty12lable" value=""> x $.95<br>
Total = <input class="qty24lable" value=""> x $1.40<br>
$("input.qty12lable").val(qty12Sum);
$("input.qty24lable").val(qty24Sum);
To set the text (value) of a textbox you have to use .val() not .text(). Like this:
$('.qty12').keyup(function() {
var qty12Sum = 0;
$('.qty12').each(function() {
if (this.value != "")
qty12Sum += parseInt(this.value);
});
$(".qty12lable").val(qty12Sum);
});
$('.qty24').keyup(function() {
var qty24Sum = 0;
$('.qty24').each(function() {
if (this.value != "")
qty24Sum += parseInt(this.value);
});
$(".qty24lable").val(qty24Sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Red
<br>12x12
<input class="qty12" value="" />
<br/>12x24
<input class="qty24" value="" />
<br>
<br>Blue
<br>12x12
<input class="qty12" value="" />
<br/>12x24
<input class="qty24" value="" />
<br>
<br>
<br>Total = <input class="qty12lable"/> x $.95
<br>Total = <input class="qty24lable"/> x $1.40
<br>
This snippet has some logic about how you can attach event listeners on input fields and how you can get their values. It's not perfect and has quite a few bugs from production level perspective but this will give a hint about how you can listen and manipulate DOM using Jquery. Which is what Jquery is all about.
$( "input" )
.change(function () {
var prevVal = ($('#total').html() !== '') ? $('#total').html() : 0;
if(parseInt($(this).val()) === NaN) {
return;
}
$('#total').html(parseInt($(this).val()) + parseInt(prevVal));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="1"></input><br>
<input type="text" id="2"></input><br>
<hr>
Total = <span id="total" class="qty12lable"></span> <br>

Radio button with search box for HTML table

I have jQuery and table shown below:
console.clear();
function inputSelected(val) {
$("#result").html(function() {
var str = '';
$(":checked").each(function() {
str += $(this).val() + " ";
});
if (val == 1) {
return $('#testSearch').val();
}
str += $('#testSearch').val();
return str;
});
}
$(document).ready(function() {
$("input[type=radio]").click(inputSelected);
$("td.other").click(function() {
$(this).find('input[type=text]').focus();
});
$('#testSearch').on('input propertychange paste', function() {
inputSelected(1);
})
$("td.other input[type=text]").keyup(function(e) {
var value = $(this).val().trim();
if (value.length <= 0) {
value = 'Other';
}
$(this).parent().siblings("input[type=radio]").val(value);
$(this).parent().siblings("label").html(value);
inputSelected();
})
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<table>
<tr>
<td><input name="test" type="radio" value="You enter A" id="1" />A</td>
<td class="other"><input name="test" type="radio" value="" id="2"/>Other:
<div class="text">
<input type="text" id="other" value="">
</div>
</td>
<td><input name="test" type="radio" value="" id="3"/>Search<input id='testSearch' type="search" name="search" placeholder="Search...">
</td>
</tr>
</table>
<div id="result">
</div>
In this table I have 3 radio buttons:
Simple Radio Button
Radio Button with input box
Radio Button with search box
Like first 2 radio buttons 3rd 'search box' button is not working. For example when I click radio button 'a', it display "You enter A" then I click radio button 'other' and enter some text, on result it hide my last selected button display and show me whatever I type. Same if I select 'search' radio button it hide last selected button display and show me whatever I type.
But
After entering something to search when I clicked on any other 2 radio button, it did not hide text that I insert to search.
So, my problem is that when I select any one radio button, it should hide previous selected output like radio button 'A' and 'other' do.
Kindly advise me what changes I have to make in this script for such purpose. Thanks
Catch.
Also I commented some of Your code.
function inputSelected(val) {
$("#result").html(function() {
if (val == 1) {
return $('#testSearch').val();
}
var str = '';
$(":checked").each(function() {
str += $(this).val() + " ";
});
//str += $('#testSearch').val();
return str;
});
}
$(document).ready(function() {
$("input[name=test]").click(inputSelected);
$("td.other").click(function() {
$(this).find('input[type=text]').focus();
});
$('#testSearch').on('input propertychange paste', function() {
$("input[class=testSearch]").val($('input[id=testSearch]').val());
if($("input[class=testSearch]").is(':checked')){
inputSelected(1);
}
})
$("td.other input[type=text]").keyup(function(e) {
var value = $(this).val().trim();
if (value.length <= 0) {
value = 'Other';
}
$(this).parent().siblings("input[type=radio]").val(value);
$(this).parent().siblings("label").html(value);
inputSelected();
})
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<table>
<tr>
<td><input name="test" type="radio" value="You enter A" id="1"/>A</td>
<td class="other"><input name="test" type="radio" value="" id="2"/>Other:
<div class="text">
<input type="text" id="other" value="">
</div>
</td>
<td><input name="test" class="testSearch" type="radio" value="" id="3"/>Search<input id='testSearch' type="search" name="search" placeholder="Search...">
</td>
</tr>
</table>
<div id="result"></div>

how will i enabled button when two textbox is equal

i tried this codes but it seems not working. my problem is how will i enabled the button when the two textbox is equal the value? the selected textbox is automatic will change depend on the quanity of item selected in multiple select.
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script>
function getCount(){
var comboBoxes = document.querySelectorAll("#tags");
var selected = [];
for(var i=0,len=comboBoxes.length;i<len;i++){
var combo = comboBoxes[i];
var options = combo.children;
for(var j=0,length=options.length;j<length;j++){
var option = options[j];
if(option.selected){
selected.push(option.text);
}
}
}
$('#selected').val(selected.length);;
}
</script>
<script>
function disableSubmit(){
var firstValue = $("#quantitytotransfer").val();
var secondValue = $("#selected").val();
if ((firstValue == secondValue)) {
$("#submit").attr("disabled", false);
}else{
$("#submit").attr("disabled", true);
}
}
$("#selected").on("keyup", disableSubmit);
$("#quantitytotransfer").on("keyup", disableSubmit);
</script>
<input name="imei" placeholder="quantity" id="quantitytotransfer">
<input name="numberselected" readonly id="selected">
<select id="tags" onchange="getCount()"multiple style="width: 200px;">
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="ccc">ccc</option>
</select>
<button id="submit" id="submit" disabled type="button">Get Values</button>
<script>
</script>
It's very easy here is the code
<input name="imei" placeholder="quantity" id="quantitytotransfer">
<input name="numberselected" readonly id="selected">
<select id="tags" multiple style="width: 200px;">
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="ccc">ccc</option>
</select>
<button id="submit" disabled type="button">Get Values</button>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
$(function() {
$("#tags").on("change", function(e) {//Whenever tags are changed it will be called
$('#selected').val($(this).find('option').filter(":selected").length);//this will set the count or length of selected length
$("#submit").prop("disabled", !$("#quantitytotransfer").val() || !$("#selected").val() || ($("#quantitytotransfer").val() != $("#selected").val()));//this will disable or enable depending on equal value
});
var delay = (function() {// a delay function
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$('#quantitytotransfer, #selected').keyup(function() {//both text box are binded to event
delay(function() {
$("#submit").prop("disabled", !$("#quantitytotransfer").val() || !$("#selected").val() || ($("#quantitytotransfer").val() != $("#selected").val()));//this will disable or enable depending on equal value
}, 1000 );//a 1 second delay used you can change to more less
});
});
You can compare value entered in input tag and selected from select tag in the following way:
Here how does it work:
Listen to input on input.
Listen to change on select tag.
When user enter a value in input, run logic enable button.
When user select a value in select, run logic enable button.
Logic enable button, compare value entered and selected from input and select tag. If both values match, button is enabled otherwise is disabled.
When a value change on select tag, show value in read-only input tag/
(function() {
var elmQuantity = $('#quantitytotransfer'),
elmTags = $('#tags'),
elmSubmit = $('#submit'),
elmSelected = $('#selected'),
findTagsSelected = function() {
return elmTags.find(':selected').text();
},
enableBtn = function() {
if (elmQuantity.val() === findTagsSelected()) {
elmSubmit.prop('disabled', false)
} else {
elmSubmit.prop('disabled', true)
}
};
elmQuantity.on('input', function() {
enableBtn();
}),
elmTags.change(function(value) {
enableBtn();
elmSelected.val(findTagsSelected());
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="imei" placeholder="quantity" id="quantitytotransfer">
<input name="numberselected" readonly id="selected">
<select id="tags" multiple style="width: 200px;">
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="ccc">ccc</option>
</select>
<button id="submit" id="submit" disabled type="button">Get Values</button>

Categories

Resources