How to extract form element values in a loop? - javascript

I have a list of form elements that I want to loop over to get the values of, so if someone typed their name in the input i want their name, if they selected an option from a select box I want the not the numerical value but the string. All these values needs to be outputted as one string.
This is the loop i've created, I however have no idea how to go about this problem..
every form element has a name starting with credit_
if someone could point me in the right direction it would be much appreciated..
$(this).parent().parent().find('[name*=credit_]').each(function( index ){
});
my html is quite simple.
<div class="comp-row">
<!-- a select -->
<!-- an input -->
</div>
This is part of the form, there are many other form fields but im only concerned with the ones within "comp-row" which Im manipulating a lot.
I ended up using:
$('.comp-row [name*="credit_"]:not([type=hidden])')
.each(function(index,elem)
{
console.log($(this).text() != '' ? $(this).find('option:selected').text().trim() : $(this).val());
});
}

Youre looking for the $('select[name*="credit_"]>option:selected') selector.
To read the text value for your , issue .text()
Combine this with if($('input[name*="credit_"]').text() != '') evaluation, combined something like this:
var theName = $('input[name*="credit_"]').text() != ''
? $('select[name*="credit_"]>option:selected').text()
: $('input[name*="credit_"]').text();

Depending on format you want you can use serialize() or serializeArray().
For example to obtain for whole form:
var data=$('#myForm').serialize()
For specific group of elements:
$('[name*=credit_]').serializeArray()
serialize() API docs
serializeArray() API docs

var result = '';
$(this).parent().parent().find('[name*=credit_]').each(function( index ){
result += $(this).is("select") ? $(this).text() : $(this).val();
});

Iterate over all elements that match your criteria (name*=credit_). Check its type and put the value inside a variable.
HTML
<form>
<input type="text" name="credit_a" value="1" />
<input type="text" name="credit_b" value="2" />
<input type="text" name="credit_c" value="3" />
<select name="credit_d">
<option value="kk">kk</option>
<option value="jj" selected>jjjjj</option>
</select>
<input name="credit_e type="checkbox" checked value="imchecked" />
</form>
<form>
<input type="text" name="credit_a" value="55" />
<input type="text" name="credit_b" value="66" />
<input type="text" name="credit_c" value="77" />
<input type="text" name="credit_d" value="88" />
</form>
<p id="result"> </p>
javascript
$(function() {
var values = '';
$('form [name*=credit_]').each(function() {
var $this = $(this);
if($this[0].tagName == 'TEXTAREA') {
values += ' ' + $this.text();
}
else if ($this[0].tagName == 'SELECT') {
values += ' ' + $this.find(':selected').text();
}
else {
values += ' ' + $this.val();
}
});
$('#result').html(values);
});
jsfiddle: http://jsfiddle.net/5tgzr/2/

Related

How to remove displayed value from td and replace with input field?

I have dynamic table that display names and input fields. If name is displayed in table row user have option to delete that name. I know how to remove value from specific table row but I have problem replacing that same spot with input field that should be the same as other available fields. Here is my code that I have so far:
<cfoutput>
<tr>
<td>#TimeFormat(CurrentTime,'hh:mm tt')#</td>
<td onClick="deleteSlot('#TimeSlotID#')">
<cfif UserID GT 0>
<label>
<div id="#TimeSlotID#">
(<b>#First# #Last#</b>)
<img src="images/delete.png"/>
</div>
</label>
<cfelseif UserID EQ -1>
<label>
<input type="text" name="email" id="email#currentRow#" class="email">
<input type="button" name="slot" id="slot#currentRow#" class="slot" value="Save" onClick="saveTime(this,'#TimeSlotID#')" style="display: none">
</label>
</cfif>
</td>
</tr>
</cfoutput>
JavaScript:
//This code display save button if user start typing in available field.
$(document).ready(function() {
$(".email").keyup(function(e) {
if($(this).val() != '') {
$(".email").not(this).attr('disabled','disabled');
$(this).next(".slot").show();
} else {
$(".email").removeAttr('disabled');
$(this).next(".slot").hide();
}
});
});
//This is the code where I'm trying to remove name from the cell and replace with input field
function deleteSlot(TimeSlotID){
$('#' + TimeSlotID).replaceWith('<label><input type="text" name="email" id="email#currentRow#" class="email"><input type="button" name="slot" id="slot#currentRow#" class="slot" value="Save" onClick="saveTime(this,'#TimeSlotID#')" style="display: none"></label>');
}
This code that I currently use in deleteSlot function does replace name with input field but if I start typing in that field I do not have Save button showed up like in the others. I'm not 100% sure if this can be done the way I started or I should use something else. I tried append but that did not work, gave me extra input fields every time I clicked. If anyone knows better way to fix this please let me know.
I believe the event keyup needs to be re-applied:
$(document).ready(function() {
applyKeyUp();
});
function applyKeyUp() {
$(".email").keyup(function(e) {
if($(this).val() != '') {
$(".email").not(this).attr('disabled','disabled');
$(this).next(".slot").show();
} else {
$(".email").removeAttr('disabled');
$(this).next(".slot").hide();
}
});
}
function deleteSlot(TimeSlotID){
$('#' + TimeSlotID).replaceWith('<label><input type="text" name="email" id="email#currentRow#" class="email"><input type="button" name="slot" id="slot#currentRow#" class="slot" value="Save" onClick="saveTime(this,'#TimeSlotID#')" style="display: none"></label>');
applyKeyUp();
}
The issue is with weirdness of the id you are passing.Since the id is already having '#' in front of it, the jquery selector would not be able to apply the target by id. If you really need '#' in front of the id, then you need to apply id equal to selector.
$('#' + TimeSlotID)
should be
$("[id = '" + TimeSlotID + "']")
Example : https://jsfiddle.net/DinoMyte/6d5ry9br/5/

HTML/Javascript Input type="text" - How to shows text different from value?

Actually i have a datalist:
<datalist id='modelsList'>
<option value='1'>Dummy1</option>
<option value='2'>Dummy2</option>
</datalist>
This is used in an input:
<input type='text' name='dummy' autocomplete='off' list='modelsList' value=''/>
If i start typing Dummy2 and then i click on the dropdown list result the textbox shows 2. I need to find a way to have 2 as value but Dummy2 as text.
I cannot use a drop-down list (select tag)
Here, my solution as per you want check it out...
You can use input event for achieving such functionality,
HTML
<input type='text' id='dummy' list='modelsList'/>
<datalist id='modelsList'>
<option value='1'>Dummy1</option>
<option value='2'>Dummy2</option>
</datalist>
Jquery
$("#dummy").on('input', function () {
var val = this.value;
if($('#modelsList option').filter(function(){
return this.value === val;
}).length) {
var option = $('#modelsList').find('option[value="' + val + '"]');
$(this).val(option.text());
}
});
also check DEMO of the above code.
The format for a text input in HTML5 is as follows:
<input type="text" name="name" value="Value" placeholder="Placeholder Text">
As a user types in their content, the value changes.
You may be getting confused with textarea:
<textarea name="name">Value</textarea>
If you want to put a textarea tag, you have to know that the value attribute is invalid, but perhaps if you want to use it instead of input, and the format is similar as you put:
<textarea name="name">contentHere</textarea>

Repeative values occur in Autocomplete jquery

I am working in ASP.NET Project.My task is to Prevent the repative values occured in Textbox.Textbox is bound with autocomplete and appending text from checkboxlist as like in the below picture
! https://drive.google.com/file/d/0B5OPwgmPG6QpTHBTdVlFaldRaEE/view?usp=sharing
After i appended the content from checkbox list to textbox means it is repeating value,if i typed it inital time it won't.And my task is to show unique values based on the textbox content.
My project files are in the below link..please help me out guys
https://drive.google.com/file/d/0B5OPwgmPG6QpS3NMNElGN2k4RzQ/view?usp=sharing
Based on my answer I gave you in the other thread (https://stackoverflow.com/a/28828842/4569271) I extended my solution to only display unique values:
$(function() {
$('input[type="checkbox"]').change(function() {
// Reset output:
$("#output").html('');
// remeber all unique values in this array:
var tmpArray = new Array();
// Repeat for all checked checkboxes:
var checkboxes = $('input[type="checkbox"]:checked').each(function() {
// Get value from checkbox:
var textToAppend = $(this).val();
// Check if value from checkbox was added already:
if (jQuery.inArray(textToAppend, tmpArray) == -1) {
// add entry to array so it will be not added again:
tmpArray.push(textToAppend);
var existingText = $("#output").html();
// Append seperator (';') if neccessary:
if (existingText != '') {
existingText = existingText + ";";
}
// Print out append value:
$("#output").html(existingText + textToAppend);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Select:</h2>
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Mar" />Mar
<input type="checkbox" value="Mar" />Mar
<input type="checkbox" value="Mar" />Mar
<h2>Output:</h2>
<div id="output"></div>
Based on your description, I am not sure if this is the solution you were looking for? But maybe it helps.

Set the hidden radio button value through autocomplete

When a user messages another user. They can pick which type of profile to send to. (Common or Manager)... I'm checking in the backend which profile to send it to with "recipient_type", How do I get my autocomplete to choose the hidden radio button for me?
The autocomplete looks like this:
To: John Doe - Manager
or
To: John Doe
template:
<div class="hide">
<input type="radio" id="id_recipient_type" name="recipient_type" value="0" />
<input type="radio" id="id_recipient_type" name="recipient_type" value="1" />
</div>
<div class="inline-block">
<label for="id_omnibox"></label>
<input type="hidden" name="recipient_username" id="id_recipient_username" />
<input id="message-to" class="required input-text" style="width: 145%;"name="omnibox" placeholder="Search for user..." autocomplte="on" type="text" />
</div>
script:
$(document).ready(function(){
$.get('/autocomplete/message/', function(data) {
var completions = new Array();
var dict = JSON.parse(data, function(key, value) {
completions.push(key);
return value;
});
$('#message-to').autocomplete({
source: completions,
minLength: 1,
select: function(value, data){
$('#id_recipient_username').val(dict[data.item.value])
split_string = data.item.value.split("- ");
$('#id_recipient_type_'+(split_string[1]=="Manager"?"1":"0")).attr('checked', true);
}
});
});
});
It seems that in order to your code to work you need to change or:
<div class="hide">
<input type="radio" id="id_recipient_type_0" name="recipient_type" value="0" />
<input type="radio" id="id_recipient_type_1" name="recipient_type" value="1" />
</div>
Radio boxes IDs. or:
$('#id_recipient_type[value="'+(split_string[1]=="Manager"?"1":"0")+'"]').attr('checked', true);
The jquery selector to #id_recipient_type[value="1"] or #id_recipient_type[value="0"].
I'd ratter use the first solution, since in html ids should be unique.
You need to solve a problem stated by kmfk with your split where it throws an error when don't find the ' - ' string, so change:
split_string = data.item.value.split("- ");
To:
split_string = 'John Doe - Manage'.match(/ - (Manager)$/)
split_string = split_string != null ? "0" : "1";
Looking through your code example, these lines appear to be the issue:
split_string = data.item.value.split("- ");
$('#id_recipient_type_'+(split_string[1]=="Manager"?"1":"0")).attr('checked', true);
That split will be an issue when - Manager is not in the the string - and the IDs you are looking for don't exist.
Maybe do:
var valAttr = data.item.value.indexOf("- Manager") > 0 ? 1 : 0;
$('#id_recipient_type [value="'+valAttr+'"]').attr('checked', true);

How do I move focus to next input with jQuery?

I am using the autocomplete plugin with jQuery and it is working fine. However, in IE, when the user selects an item in the autocomplete, the focus does not then move to the next input field. Naturally it works in Firefox. The plugin doesn't have a built-in solution but does provide for "options". Is there a way I can force it to move to the next input field?
You can do something like this:
$("input").change(function() {
var inputs = $(this).closest('form').find(':input');
inputs.eq( inputs.index(this)+ 1 ).focus();
});
The other answers posted here may not work for you since they depend on the next input being the very next sibling element, which often isn't the case. This approach goes up to the form and searches for the next input type element.
JQuery UI already has this, in my example below I included a maxchar attribute to focus on the next focus-able element (input, select, textarea, button and object) if i typed in the max number of characters
HTML:
text 1 <input type="text" value="" id="txt1" maxchar="5" /><br />
text 2 <input type="text" value="" id="txt2" maxchar="5" /><br />
checkbox 1 <input type="checkbox" value="" id="chk1" /><br />
checkbox 2 <input type="checkbox" value="" id="chk2" /><br />
dropdown 1 <select id="dd1" >
<option value="1">1</option>
<option value="1">2</option>
</select><br />
dropdown 2 <select id="dd2">
<option value="1">1</option>
<option value="1">2</option>
</select>
Javascript:
$(function() {
var focusables = $(":focusable");
focusables.keyup(function(e) {
var maxchar = false;
if ($(this).attr("maxchar")) {
if ($(this).val().length >= $(this).attr("maxchar"))
maxchar = true;
}
if (e.keyCode == 13 || maxchar) {
var current = focusables.index(this),
next = focusables.eq(current+1).length ? focusables.eq(current+1) : focusables.eq(0);
next.focus();
}
});
});
What Sam meant was :
$('#myInput').focus(function(){
$(this).next('input').focus();
})
Try using something like:
var inputs = $(this).closest('form').find(':focusable');
inputs.eq(inputs.index(this) + 1).focus();
why not simply just give the input field where you want to jump to a id and do a simple focus
$("#newListField").focus();
Use eq to get to specific element.
Documentation about index
$("input").keyup(function () {
var index = $(this).index("input");
$("input").eq(index + 1).focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" maxlength="1" />
<input type="text" maxlength="1" />
<input type="text" maxlength="1" />
<input type="text" maxlength="1" />
<input type="text" maxlength="1" />
<input type="text" maxlength="1" />
you can use
$(document).on("keypress","input,select",function (e) {
e.preventDefault();
if (e.keyCode==13) {
$(':input).eq($(':input').index(this) + 1)').focus();
}
});
Could you post some of your HTML as an example?
In the mean-time, try this:
$('#myInput').result(function(){
$(this).next('input').focus();
})
That's untested, so it'll probably need some tweaking.
I just wrote a jQuery plugin that does what you are looking for (annoyed that that I couldn't find andy solution myself (tabStop -> http://plugins.jquery.com/tabstop/)
function nextFormInput() {
var focused = $(':focus');
var inputs = $(focused).closest('form').find(':input');
inputs.eq(inputs.index(focused) + 1).focus();
}
if you are using event.preventDefault() in your script then comment it out because IE doesn't likes it.
The easiest way is to remove it from the tab index all together:
$('#control').find('input[readonly]').each(function () {
$(this).attr('tabindex', '-1');
});
I already use this on a couple of forms.
Here is what worked in my case. Might be less performance intensive.
$('#myelement').siblings('input').first().focus();
var inputs = $('input, select, textarea').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
var nextInput = inputs.get(inputs.index(this) + 1);
if (nextInput) {
nextInput.focus();
}
}
});
onchange="$('select')[$('select').index(this)+1].focus()"
This may work if your next field is another select.

Categories