how to separate and display select option data? - javascript

I have two forms. form1's content is a choice option filled by name, matricule, and salary, and a button validate, which hides form1 and displays form2. I want when I click on the button, the contents of select to separate and show like this:
name:
registration number :
salary :
$(document).ready(function() {
$("#hide").click(function() {
let name1 = $('#name').text();
let matricule1 = $('#matricule').text();
let salary1 = $('#salary').text();
$('#nam').text(name1);
$('#mat').text(matricule1);
$('#sal').text(salary1);
$("#form1").hide();
$("#form2").show();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="form1">
<div class="form-group col-md-3">
<select class="form-control">
<option>
<div id="name">imad</div>
<div id="matricule">22</div>
<div id="salary">6000</div>
</option>
</select>
</div>
<div class="form-group col-md-offset-5 ">
<button class="btn btn-success " id="hide">valider</button>
</div>
</div>
<!--form 2-->
<div id="form2">
<h4>name : <span id="nam"></span></h4>
<h4>matricule : <span id="mat"></span></h4>
<h4>salary : <span id="sal"></span></h4>
</div>

As Rory said, you cannot have HTML within an option element, this is invalid. Use a custom drop-down select library (some examples of such are here: https://www.sitepoint.com/13-jquery-selectboxdrop-down-plugins/)
Now, if you know the format of the data you are using to populate the select option values with (you are getting data from server side, etc.), you could then format the data on the client side with some sort of separator to create a chained together option value for the 3 different fields, like I've done in the example below using a dash (-). You could then split the string value of the option selected, and parse it out to individual text fields. Again, this is all dependent on how you get and format the data within the select element.
$(document).ready(function() {
$("#hide").click(function() {
let selectOption = $('.form-control').val();
let optionSplits = selectOption.split('-');
let name1 = optionSplits[0];
let matricule1 = optionSplits[1];
let salary1 = optionSplits[2];
$('#nam').text(name1);
$('#mat').text(matricule1);
$('#sal').text(salary1);
$("#form1").hide();
$("#form2").show();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="form1">
<div class="form-group col-md-3">
<select class="form-control">
<option value="imad-22-6000">imad 22 6000</option>
<option value="gupta-24-8000">gupta 24 8000</option>
<option value="ganesh-27-5000">ganesh 27 5000</option>
</select>
</div>
<div class="form-group col-md-offset-5 ">
<button class="btn btn-success " id="hide">valider</button>
</div>
</div>
<!--form 2-->
<div id="form2">
<h4>name : <span id="nam"></span></h4>
<h4>matricule : <span id="mat"></span></h4>
<h4>salary : <span id="sal"></span></h4>
</div>

Related

How can I pass the value from drop down list as a link for button?

I am creating a web app (using thymeleaf, html, css, javascript) and I ran into a problem. Say I have a search bar and a button like this:
Now this represents the functionality of an app and currently it can only search records from a table by their name. But I want to add some other functions like "search by population", "search by capital" etc. I was planning on creating a drop-down list next to the search bar where these options will be included, and the user will select from that list how he wants to search for a record. I can't see a way to do that. Currently this is a search bar code:
<h4 class="left">
<form ui-jp="parsley" th:action="#{/events/showByState}" th:object="${myState}" method="get">
<div class="row m-b">
<div class="child">Search by State Name:</div>
<div class="child"><input id="filter" type="text" th:field="*{officialStateName}" class="form-control input-sm w-auto inline m-r"/></div>
<div class="child box-3">
<button class="btn">Search!</button>
</div>
</div>
</form>
</h4>
So it is unclear for me how I do this because I need to specify the link for button based on what user will choose from the list. Any help is appreciated!
You can create a <select> element with options whose value indicate what the action of the form should be. Whenever its value changes, you can update the form's action.
document.getElementById('search-by').addEventListener('change', function(e) {
let searchBy = this.value;
console.log(searchBy);
this.form.action = `/events/${searchBy}`;
});
<form ui-jp="parsley" th:action="#{/events/showByState}" th:object="${myState}" method="get">
<div class="row m-b">
<div class="child">Search by
<select id="search-by">
<option value="showByState">State Name</option>
<option value="showByPopulation">Population</option>
<option value="showByCapital">Capital</option>
</select>:</div>
<div class="child"><input id="filter" type="text" th:field="*{officialStateName}" class="form-control input-sm w-auto inline m-r" /></div>
<div class="child box-3">
<button class="btn">Search!</button>
</div>
</div>
</form>

How to get updated form input value via jQuery/Javascript?

I see lots of discussion about setting and getting a field value via jQuery. But my issue is that I am unable to get a value after I submit, then edit the value in an input field, then submit again. So the first time it works, the second time it doesn't.
Here's my scenario: I have a form that is used to manage filters for a dataset:
<form id="filtersForm">
<div class="row">
<div class="col-md-12">
<div id="addContactFilter">
<div class="row filterRow" id="contact_filter_780b902d">
<div class="col-md-4">
<!-- Selectize dropdown of fields to query by -->
<div class="control-group">
<select id="filterField_780b902d" class="selectizeField selectized" name="filterField_780b902d" placeholder="Select field..." tabindex="-1" style="display: none;">
<option value="firstName" selected="selected">First Name</option>
</select>
<div class="selectize-control selectizeField single">
<div class="selectize-input items has-options full has-items">
<div data-value="firstName" class="item">First Name</div>
<input type="text" autocomplete="off" tabindex="" style="width: 4px; opacity: 0; position: absolute; left: -10000px;">
</div>
<div class="selectize-dropdown single selectizeField" style="display: none; visibility: visible; width: 248px; top: 34px; left: 0px;">
<div class="selectize-dropdown-content">
<div data-value="firstName" data-selectable="" class="option selected">First Name</div>
<div data-value="lastName" data-selectable="" class="option">Last Name</div>
<div data-value="organization" data-selectable="" class="option">Organization</div>
<div data-value="jobTitle" data-selectable="" class="option">Job Title</div>
<div data-value="city" data-selectable="" class="option">City</div>
<div data-value="state" data-selectable="" class="option">State</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<select id="filterOperator_780b902d" class="form-control">
<option value="=">equals</option>
<option value="contains">contains</option>
</select>
</div>
<div class="col-md-4">
<div id="contact_filter_value_780b902d">
<!-- THIS IS THE FIELD IN QUESTION -->
<input class="form-control" type="text" name="filterValue_780b902d" id="filterValue_780b902d" data-type="String" placeholder="Input Value">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row filterCriteria">
<div class="col-md-12">
<input class="btn btn-default" type="submit" value="Submit">
</div>
</div>
</form>
When I first submit the form, I am able to successfully get the value for the input field with id #filterValue_780b902d. But if the user edits the value in the form, then submits again, the original value is returned.
Here's how I try to retrieve the value (I am using Meteor JS, which provides an event map on the click event with an event parameter):
var target = event.target,
fieldName = 'filterValue_' + fieldId;
thisVal1 = target[fieldName].value,
thisVal2 = template.find( "[name='" + fieldName + "']" ).value,
thisVal3 = $( '#' + fieldName ).attr('value'),
thisVal4 = $( '#' + fieldName ).val();
When I submit the form the first time with the input value "Meghan", here's the response logs:
contactFilters.filtersForm submit
contactFilters.filtersForm.fieldId: 780b902d
contactFilters.filtersForm.fieldName: filterValue_780b902d
contactFilters.filtersForm.thisVal1: Meghan
contactFilters.filtersForm.thisVal2: Meghan
contactFilters.filtersForm.thisVal3: undefined
contactFilters.filtersForm.thisVal4: Meghan
But when I change the input value to "Karen", here's what I get:
contactFilters.filtersForm submit
contactFilters.filtersForm.fieldId: 780b902d
contactFilters.filtersForm.fieldName: filterValue_780b902d
contactFilters.filtersForm.thisVal1: Meghan
contactFilters.filtersForm.thisVal2: undefined
contactFilters.filtersForm.thisVal3: undefined
contactFilters.filtersForm.thisVal4: undefined
So three questions:
Why does thisVal1 not update when the text of the field is updated?
Why does thisVal2 and thisVal4 become undefined?
What's the proper way to get the field value that will update when the input field value updates?
Thanks in advance for your help!
i believe the correct way to get value in jQuery is to use the val() function.
so you should probably be using:
var target = event.target,
fieldName = 'filterValue_' + fieldId;
myValue = $( '#' + fieldName ).val();
as stated here:
https://stackoverflow.com/a/15903284/6368401
and here:
http://api.jquery.com/val/
in javascript
document.getElementById("input_id").value
other javascript methods explained here:
How do I get the value of text input field using JavaScript?
to answer your 'undefined' questions:
var target = event.target,
fieldName = 'filterValue_' + fieldId;
thisVal1 = target[fieldName].value,
this is getting the original value from the postback.
thisVal2 = template.find( "[name='" + fieldName + "']" ).value,
i cant answer this one, as i dont know the answer
thisVal3 = $( '#' + fieldName ).attr('value');
the attribute "value" was never defined in the markup.

I want to access discount prize but its not getting

In this code I want to calculate discount present.
There is one offer selection list if we select offer as yes then I shows <div id="dis11"> i.e. ($("#dis11").show();). There is jquery call. In that div four text boxes are there offerstart date, end date, discount prize, discount%. I want to take discount prize in jquery call, but I didn't get it.
adis=document.getElementById("discount").value;
that's the problem.
In this there is prize text box which contains original prize of product. Using that prize and discount prize I have to calculate discount persent. On prize text box I gave onblur event. Bez if prize change discount present also going to change.
<div class="formrow1">
<div class="txttitle_large1">Prize</div>
<div class="txtinputouter1">
<input type="text" name="prize" id="prize1" onblur="prizf();">
</div>
</div>
</div>
<div class="txttitle" style="width:30px;">Offer</div>
<div class="txtinputouter1">
<select class="required" name="offer" id="offers" onChange="discountajax();">
<option value="11">--Select offer--</option>
<option value="1">yes</option>
<option value="0">no</option>
</select>
<div id="discountinfo">
</div>
</div>
<div style="width:70%;height:auto;float:left;margin-top:10px; display:none;" id="dis11">
<div class="formrow1">
<div class="txttitle_large1">OfferStart</div>
<div class="txtinputouter1">
<input type="text" name="offerstart" id="offerstart"/>
</div>
</div>
<div class="formrow1">
<div class="txttitle_large1">OfferEnd</div>
<div class="txtinputouter1">
<input type="text" name="offerEnd" id="offerEnd"/>
</div>
</div>
<div class="formrow1">
<div class="txttitle_large1">Discount Prize</div>
<div class="txtinputouter1">
<input type="text" name="discountprize" id="discount"/>
</div>
</div>
<div class="formrow1">
<div class="txttitle_large1">Discount%</div>
<div class="txtinputouter1">
<input type="text" name="discountpercent" id="discountpercent"/>
</div>
</div>
</div>
--------script---------------
<script>
function prizf()
{
alert("hi");
discountajax();
}
</script>
<script>
function discountajax()
{
p=document.getElementById("prize1").value;
alert(p);
id1=document.getElementById("offers").value;
alert(id1);
if(id1==1)
{
$("#dis11").show();
adis=document.getElementById("discount").value;
alert(adis);
}
}
</script>
Explanation
Your function prizf run only two times. one starting and second onchange but you are able to get the value of discount when it start to visible for entering values.
you are getting undefined $ error because jquery is not included.
I create a function for getting value of discount.
check the below code.
BTW this is not the standard code.
<script>
function discountajax()
{
p = document.getElementById("prize1").value;
//alert(p);
id1 = document.getElementById("offers").value;
if (id1 == 1)
{
// alert("id"+id1);
$("#dis11").show();
adis = document.getElementById("discount").value;
alert(adis);
}
}
$(document).ready(function () {
$("#discount").focusout(function () {
prizf();
})
})
</script>

Hide/Unhide DIV with JQuery

I'm pulling the variables from a database and the values could either be Manual or Automatic. Users can also use a dropdown to change the values.
If the value is already Manual I need it to unhide a DIV or if it was Automatic and the user switches to Manual I need to unhide a DIV.
What I have currently only unhides if it was Automatic and user selects Manual.
Here is a JSFiddle: http://jsfiddle.net/DTcHh/5031/
Any help would be appreciated.
Thanks!
HTML:
<form class="form-horizontal" method="post">
<div class="form-group">
<label class="col-md-5 control-label" for="method">Method:</label>
<div class="col-md-6">
<select id="method" name="method" class="form-control">
<option value="Automatic">Automatic</option>
<option value="Manual">Manual</option>
</select>
</div>
</div>
<div id="manual" class="panel panel-default" style="display:none">
<div class="panel-heading">
<h4 class="panel-title">
Manual
</h4>
</div>
<div class="panel-body">
<div class="form-group">
<label class="col-md-5 control-label" for="activitycomplete">Activity Complete:</label>
<div class="col-md-6">
<select id="activitycomplete" name="activitycomplete" class="form-control">
<option value="False">False</option>
<option value="True">True</option>
</select>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-actions">
<button type="submit" class="btn btn-success">Update</button>
<button type="button" data-dismiss="modal" class="btn btn-default">Back</button>
</div>
</form>
JQuery:
$(document).ready(function () {
$('#method').change(function () {
$('#manual').toggle(500);
});
//$("#method").val('Manual');
});
There's no logic in the code which actually checks the value. Basically, this rule isn't implemented:
If the value is already Manual I need it to unhide a DIV or if it was Automatic and the user switches to Manual I need to unhide a DIV.
The code is assuming that the initial value is always "Automatic" and that there will always ever be a one-way-or-the-other switch between the two values. This assumption is incorrect.
Instead of assuming the value and just toggling, explicitly show/hide based on the inspected value:
$('#method').change(function () {
if ($(this).val() == 'Manual') {
$('#manual').show(500);
} else {
$('#manual').hide(500);
}
});
Which you can extract into a function so it can be invoked manually as well:
var toggleDiv = function () {
if ($('#method').val() == 'Manual') {
$('#manual').show(500);
} else {
$('#manual').hide(500);
}
}
$('#method').change(toggleDiv);
Then you can invoke it when the page first loads as well:
$("#method").val('Manual');
toggleDiv();
Example here.
You'll want to check the value of the dropdox and on page load if it is manual run the toggle function:
$(document).ready(function () {
$('#method').change(function () {
$('#manual').toggle(500);
});
var valueOfDropDown = $('#method').val();
if(valueOfDropDown === "Manual"){
$('#manual').toggle(500);
}
});
This will obviously show the box on once the dom is ready.

Can't get value of textarea using Javascript

I have a form which is using the SheepIt jQuery plugin, for duplication of form rows. One of the elements in the row is a <select> element. When a certain value is chosen in the select value, a modal (I'm using Fancybox on my site) containing a <textarea> appears, allowing users to provide additional information. My idea was to take this text and add it to the form in a hidden form element, but I can't for the life of me get the text using jQuery. I've tried using .val(), .text(), and .html(), but I keep getting an empty string. I even tried using vanilla Javascript using similar methods to above, but I still can't get it to work. I have a hidden element (<input type="hidden" id="row_id" value="" />) in that same block of HTML and have no problem retrieving it using $("#row_id").val(). Any suggestions?
My Code
HTML
<!-- sheepIt Form -->
<div id="meta_fields" class="well sheepit-form">
<!-- Form template-->
<div id="meta_fields_template" class="sheepit-row">
<input id="meta_fields_#index#_field_label" name="meta[meta_fields][#index#][field_label]" type="text" placeholder="Field Label" />
<select id="meta_fields_#index#_field_type" name="meta[meta_fields][#index#][field_type]" class="field-choice">
<option value="">--Field Type--</option>
<option value="text">Single Line Text Box</option>
<option value="textarea">Multi Line Text Box</option>
<option value="checkbox">Checkbox</option>
<option value="select">Dropdown List</option>
</select>
<input id="meta_fields_#index#_field_id" name="meta[meta_fields][#index#][field_id]" type="hidden" />
<input id="meta_fields_#index#_field_required" name="meta[meta_fields][#index#][field_required]" value="0" type="hidden" />
<input id="meta_fields_#index#_field_required" name="meta[meta_fields][#index#][field_required]" value="1" type="checkbox" />
<label for="meta_fields_#index#_field_required">Required?</label>
<a id="meta_fields_remove_current" class="item small">
<i class="icon-remove"></i>
</a>
</div>
<!-- /Form template-->
<!-- No forms template -->
<div id="meta_fields_noforms_template">No fields defined!</div>
<!-- /No forms template-->
<!-- Controls -->
<div id="meta_fields_controls" class="sheepit-buttons">
<span id="meta_fields_add"><button class="btn btn-success btn-small"><i class="icon-plus-sign"></i> <span>Add Row</span></button></span>
<span id="meta_fields_remove_last"><button class="btn btn-warning btn-small"><i class="icon-remove"></i> <span>Remove Row</span></button></span>
<span id="meta_fields_remove_all"><button class="btn btn-danger btn-small"><i class="icon-trash"></i> <span>Remove All Rows</span></button></span>
</div>
<!-- /Controls -->
</div>
<!-- /sheepIt Form -->
<script type="text/x-handlebars" id="select-options-form">
<p class="lead">Please provide options for the dropdown list. One option per line</p>
<div>
<textarea id="options" style="width:500px;height:200px"></textarea>
<input type="hidden" id="row_id" value="" />
</div>
<div class="pull-right">
<button class="btn btn-success closeModal">
<i class="icon-ok"></i>
Complete
</button>
</div>
</script>
NOTE: This is not a true Handlebars template. I'm using the <script> tag to hold the HTML fragment that is inserted into the modal. I wasn't sure if having a div with style="display:none" was causing JS to think that there were two elements in the page (that was my original markup).
Javascript
// called from <select> event handler
function checkFieldList(e)
{
e.preventDefault();
var value = $(this).val();
if(value !== 'select') {
// TODO: do some processing here
return false;
}
// get the sheepIt row id -- easiest by parsing out the element ID
var row_id = parseInt($(this).prop("id").split("_")[2], 10);
return openModal(row_id);
}
function openModal(row_id)
{
// load in content and open in modal
var modalContent = $("#select-options-form");
modalContent.find("#row_id").val(row_id);
$.fancybox({
"width" : 600,
"height" : 300,
"modal" : true,
"content" : modalContent.html(),
"afterShow" : bindModalClose,
"beforeClose" : closeModal
});
}
function bindModalClose()
{
$(".closeModal").on('click', function(e) {
e.preventDefault();
$.fancybox.close();
});
}
function closeModal()
{
//add link after select dropdown and wire an event handler
var row_id = $("#row_id").val(),
dropdown = $("#meta_fields_" + row_id + "_field_type");
addOptionsLink(dropdown, row_id);
// retrieve content in <textarea>
// all the following return empty string
var text = $("#options").val();
// var text = $("#options").html();
// var text = $("#options").text();
// var text = document.getElementById("options").value;
// var text = document.getElementById("options").innerHTML;
// var text = document.getElementById("options").innerText;
console.log(text);
// 3. insert that content into hidden form field
}
function addOptionsLink(dropdown, row_id)
{
dropdown.after('View Options');
$(".load_options").on('click', function(e) {
e.preventDefault();
return openModal(row_id);
});
}
And...of course right after I resort to asking the question on StackOverflow, it's working just fine now with the $("#options").val(); solution. It's been a long week...

Categories

Resources