Add and remove input texts on button click - javascript

I have a form that allows a user to create custom questions.
The user needs to insert the title for the question and then choose the type of the question.
If the type of question is radio button, checkbox or a select menu it should appear a div "availableOptions" that shows by default two input texts so the user can insert some option values.
Doubt:
When this "availableOptions" div appears there is also a button "add new option" that when is clicked it should appear another input text so the user can insert a new option value. Each option should also have always a remove button associated that when is clicked the user can remove that input text, but it should be always a minimum of one input text.
Do you know how to do this properly? I have the working example below but it's working neither the append nor the remove.
Example: https://jsfiddle.net/udx6pp8u/15/
HTML:
<form id="" method="post" class="clearfix" action="">
<div class="form-group">
<label for="inputName">Title</label>
<input type="text" class="form-control" id="inputName">
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Type of Field</label>
<select class="form-control" id="customQuestionType">
<option>Text</option>
<option>Long text</option>
<option id="optionQuestion">Checkboxes</option>
<option id="optionQuestion">Radiobuttons</option>
<option id="optionQuestion">Select Menu </option>
</select>
</div>
<div class="form-group" id="availableOptions">
<label for="inputName">Available Options </label>
<div class="option">
<input type="text" class="form-control">
<button id="removeOption">Remove Option</button>
</div>
<div class="option">
<input type="text" class="form-control">
<button id="removeOption">Remove Option</button>
</div>
<div class="form-group">
<button type="button" class="btn btn-outline-primary mt-3" id="addNewOption">Add new Option</button>
</div>
</div>
<input type="submit" class="btn btn-primary float-right mt-3" value="Store"/>
</form>
CSS:
#availableOptions{display:none;}
jQuery:
var selected_option = $('#customQuestionType option:selected').attr('id');
if (selected_option == "optionQuestion") {
$('#availableOptions').show();
if ($('#addNewOption').click(function() {
$('#availableOptions')
.append('<div class="option"><input type="text" class="form-control"><button id="removeOption">Remove Option</button></div>');
}));
if ($('#removeOption').click(function() {
$('#availableOptions') // how to remove the clicked otpion?
}));
}

Try this:
Note: Don't use id. Use class instead. One document should only have one unique id. Using multiple id="removeOption" will coz your script to behave incorrectly and also choose the first found and ignore the rest having the same id
$('#customQuestionType').change(function(){
var selected_option = $('option:selected', this).val();
if (selected_option == "optionQuestion") {
$('#availableOptions').show();
$('#addNewOption').click(function() {
$('#availableOptions').append('<div class="option"><input type="text" class="form-control"><button id="removeOption">Remove Option</button></div>');
});
}
});
$(document).on('click', '.removeOption', function(e) {
e.preventDefault();
$(this).closest('.option').remove();
})
DEMO:
https://jsfiddle.net/dL7opvak/21/
EDITED

Related

remove specific field javascript

I have an form with some inputs. When i click on the + button, javascript create an input field. This is my form code:
<div class="row">
<div class="col-md-3">
<div id="container">
<div id="new" class="">
<input type="number" name="number" id="number">
<select class="form-control" id="sel1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</div>
</div>
</div>
</div>
<button onClick="addNumber(); New();" class="btn btn-warning btn-md" type="button">+</button>
The + button create an new option and number field. This is the Javascript code for create new fields:
function New()
{
var node = document.createElement("div");
node.setAttribute("id", "new");
node.setAttribute("class", addNumber());
node.innerHTML = $("#new").html();
document.getElementById("container").appendChild(node);
$('#container').append(node);
}
This works good, but i want delete an specific field. When the new field create's, i want also when the delete button clicked, the field deleted. How can i do this?
now add delete icon with every div and on click pass id of that div to dlete function

Load bootstrap forms from select page

I have a register form. I just need to load bootstrap form in same page behind the select menu when someone click something from select menu. Should I hide form until someone click that item in select menu right?
This is my code.
<div class="form-group">
<select class="form-control menu">
<option>Select category*</option>
<option>Apartment</option>
<option>Lands</option>
</select>
</div>
I need to load this form someone click Apartment in the menu.
<form>
<div class="col-md-12">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" placeholder="Size(sqft)">
/div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" placeholder="No of bedrooms">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" placeholder="No of bathrooms">
</div>
</div>
</div>
</div>
</form>
I tried play with this code. But it redirect to another pages.
<script>
$('select.menu').change(function(e){
// this function runs when a user selects an option from a <select> element
window.location.href = $("select.menu option:selected").attr('value');
});
</script>
What method do I need to follow?
Have a look at this jsfiddle:
I gave your wrapper of your apartment an id <div class="col-md-12" id="apartment">.
So I added following jQuery to toggle your html of your apartment:
$('select.menu').change(function(){
// this function runs when a user selects an option from a <select> element
switch($(this).find("option:selected").prop('value')) {
case '1': $('#apartment').show(); break;
default: $('#apartment').hide(); break;
}
});
And don't forget to hide your #apartment:
#apartment {
display: none;
}
window.location.href will redirect you to the new page. You can just hide your form before user make a select change or get it dynamically with jQuery.load() function.
Let's say your HTML,
<div class="form-group">
<select class="form-control menu">
<option>Select category*</option>
<option>Apartment</option>
<option>Lands</option>
</select>
</div>
by default let the form is in display:none.
Jquery,
<script>
$('select.menu').change(function(e){
// this function runs when a user selects an option from a <select> element
window.location.href = $("select.menu option:selected").attr('value');
if($(this).val == "Apartment"){
$('form').show();
}else{
$('form').hide();
}
});
</script>

jquery radio button each -not working

i am trying to loop through the radio buttons by name with 'each' function..the each function is not working and it is applying the logic only once and it is not looping for the next time..
My use case is, when user selects value from the select dropdown, needs to enable both the radio buttons and if the user deselects the dropdown- needs to disable back..
Here in my case, each function is looping only once and after that it is getting exit from it..Need help in figuring disable/enable based on dropdown selection..
html code:-
<div class="uriDiv input-group">
<select class="common authSelect form-control" name="authType" id="authType">
<option value="">
<spring:message code="newPolicy.selectAuthType"></spring:message>
</option>
<option value="DB">DB</option>
<option value="LDAP">LDAP</option>
</select>
</div>
<td>
<div class="auth-permission-rd">
<div class="uriDiv radio radio-left">
<label>
<input type="radio" class="common anyuser" value="anyUser" name="authPermission" id="authPermission" disabled="disabled">Any User
</label>
</div>
<div class="uriDiv radio radio-input">
<label>
<input type="radio" class="common groupuser" value="groupUser" name="authPermission" id="authPermission" disabled="disabled">
<input type="text" name="authPermissionValue" disabled="disabled" class="common form-control-placeHolder" id="authPermissionValue" placeholder="Enter custom Permissions - Comma separated" />
</label>
</div>
</div>
jquery:
$("#authType").change(function(){
if($(this).val()){
$("input:radio[name='authPermission']").each(function(){
$("#authPermission").prop('disabled',false);
$("#authPermission").prop('checked',false);
});
}
else{
$("#authPermission").each(function(){
$("#authPermission").prop('disabled',true);
$("#authPermission").prop('checked',false);
});
}
});
You cannot have more than one element with the same ID. So, I would change your code by removing the id attribute and putting a new value for the class attribute, then fetch the object using jquery class selector.
<div class="uriDiv input-group">
<select class="common authSelect form-control" name="authType" id="authType">
<option value="">
<spring:message code="newPolicy.selectAuthType"></spring:message>
</option>
<option value="DB">DB</option>
<option value="LDAP">LDAP</option>
</select>
</div>
<td>
<div class="auth-permission-rd">
<div class="uriDiv radio radio-left">
<label>
<input type="radio" class="common anyuser authPermission" value="anyUser" name="authPermission" disabled="disabled">Any User
</label>
</div>
<div class="uriDiv radio radio-input">
<label>
<input type="radio" class="common groupuser authPermission" value="groupUser" name="authPermission" disabled="disabled">
<input type="text" name="authPermissionValue" disabled="disabled" class="common form-control-placeHolder authPermissionValue" placeholder="Enter custom Permissions - Comma separated" />
</label>
</div>
</div>
And jQuery code :
$("#authType").change(function(){
if($(this).val()){
$("input:radio[name='authPermission']").each(function(elemId, elem){
$(elem).prop('disabled',false);
$(elem).prop('checked',false);
});
}
else{
$(".authPermission").each(function(elemId, elem){
$(elem).prop('disabled',true);
$(elem).prop('checked',false);
});
}
});
But, if we take a better look at your code, I do not understand why you want to use "each". You can achieve the same thing without it :
// Following code :
$(".authPermission").each(function(elemId, elem){
$(elem).prop('disabled',true);
$(elem).prop('checked',false);
});
// Does the same thing as this one :
$(".authPermission").prop('disabled', true).prop('checked', false);
I refactored your code. Also enables the input field when the appropriate radio is clicked. This sould work:
function updateUI() {
var select = $("#authType");
var value = select.val();
var should_appear = (value.length == 0);
$("input:radio[name='authPermission']").attr('disabled',should_appear);
}
//binding...
$("input:radio").on("click", function() {
var should_display_textbox = !($(this).val() === "groupUser");
console.log(should_display_textbox);
$("input:text[name='authPermissionValue']").attr('disabled', should_display_textbox);
});
$("#authType").change(function(){
updateUI();
});
$(document).ready(function() {
updateUI(); //update also when page load
});
Something like this maybe?
$("#authType").change(function(){
var disabled = !$(this).val() ? true : false;
$("input:radio[name='authPermission']").each(function(){
$(this).prop('disabled', disabled );
$(this).prop('checked',false);
});
});

Getting dynamic form values

Is there a way to check which like option is selected for which text box when submitted.
As shown below user may select like only for some text values. The html tags are dynamically generated based on the object parameters
for(int i = 0 ; i < object ; i++)
{
if(obj.textbox)
<input type="tex" id="obj.id"/> <input type="checkbox" id="obj.id"+"#"/>
else
<select> ... </select>
}
Right now what I do is assign a text "#" as shown above to the check box and after the form is submitted iterate all the checkbox items and get the selected value and split it and get the text value and append both value and like if selected, with | symbol and send the request.
Is there a better way to get the entered text values and check if the like option is selected for that.
This is my View Code.
<div ng-repeat="filter in filters">
<div class="content-pad">
<fieldset>
<label for="textinputID1"><p class="lead">
{{filter.dsply_name}} :
</p>
</label>
<div class="field-group" nowrap>
<input ng-if="!filter.listFlag" type="text" id='filter.atrbt_name' class="span3">
<button type="button" class="reset-field hide-text">Reset field</button>
<label class="checkbox" ng-if="!filter.listFlag">
<input id='filter.atrbt_name' type="checkbox">
<i class="skin"></i> <span>Like</span>
</label>
</div>
<div class="form-row">
<div class="row-fluid-nowrap">
<div class="span12">
<select ng-if="filter.listFlag" class="mod-select span12" ng-model="filterSelectOption" ng-options="value.displayValue as value.displayValue for value in filter.listValues">
<option value="" selected="selected">Select an Option</option>
</select>
</div>
</div>
</div>
</fieldset>
</div>
Bind the click event to submit button, in js callback function, get values & do check.

delete button for current division in HTML using javascript or JQuery

I made a dynamic form with an add button that creates a new division with the clone of the form but has a different ID. However, I also want to have a delete button with each division that removes the division that it is in, including the button itself.
I am familiar with JQuery .remove() method but I am having trouble selecting the division that the button is in.
<div id="attendees">
<div id="att1" class="attendee">
<form name="droplist" action="html_form_action.asp" method = "get">
<fieldset>
<legend><span class="legend">Filter</span></legend>
<label for="select">Category: </label>
<select id="select" size="1" >
<option value=" " selected="selected"> </option>
<option value="employees">Number of Employees</option>
<option value="hits">Hits on TechCrunch</option>
<option value="time_founded">Time Founded</option>
<option value="total_money">Total Money</option>
</select>
<div id='radioContainer' style="display:block;">
<input type="radio" id="condition" name="button" value="more"/> <label for="condition"> > </label></br>
<input type="radio" id="condition1" name="button" value="less"/> <label for="condition1"> < </label>
</div>
<div id='radioContainerTime' style="display:block;">
<input type="radio" id="condition2" name="button" value="later"/> <label for="condition"> After </label></br>
<input type="radio" id="condition3" name="button" value="earlier"/> <label for="condition1"> Before </label>
</div>
<div id = "text_box" style="display:block;">
<label for="input_value">Amount: </label>
<input type="text" id="box" name="input_value" value="textIn" />
</div>
<button>remove</button>
</fieldset>
</form>
</div>
Add more
</div>​
My JavaScript so far is this:
$(function(){
var template = $('#attendees .attendee:first').clone(),
attendeesCount = 1;
var addAttendee = function(){
attendeesCount++;
var attendee = template.clone().find(':input').each(function(){
var newId = this.id.substring(0, this.id.length-1) + attendeesCount;
$(this).prev().attr('for', newId); // update label for (assume prev sib is label)
this.name = this.id = newId; // update id and name (assume the same)
}).end() // back to .attendee
.attr('id', 'att' + attendeesCount) // update attendee id
.prependTo('#attendees'); // add to container
};
$('.add').click(addAttendee); // attach event
});
$("button").click(function () {
$this.remove();
});
To delete the <div class="attendee"> that contains the button, you can just use this:
$("button").click(function () {
$(this).closest(".attendee").remove();
return(false);
});
This looks up the parent chain from the clicked button to find the first part with a class="attendee" and then removes that.
FYI, I'd strongly suggest putting a class on your delete button because it's a little dangerous to hook up to ALL buttons in your page.
To put a class on your delete button, change the HTML to this:
<button class="deleteButton">remove</button>
And, change the jQuery to this:
$(".deleteButton").click(function () {
     $(this).closest(".attendee").remove();
     return(false);
});
The return(false) prevents any default action in the form from occurring based on the click.

Categories

Resources