How to create CheckBox onClick Event in asp.net MVC - javascript

I'm accessing the data for the CheckBoxes from the database, now I want to display the form for each and every checkbox if it's checked. How to achieve this?
My form design -
<div class="col-sm-12" id="roomtypes">
#foreach(var item in ViewBag.RoomTypes)
{
<input type="checkbox" id="chk_#item.id" name="RoomTypes" value="#item.id" /> #item.type<br />
<div class="col-sm-12" style="display:none;" id="Price_#item.id">
<input type="number" placeholder="Enter Price" id="PriceValue" />
</div>
}
</div>
I want to display the price input when checkbox is checked.
My back-end code -
ViewBag.RoomTypes = db.RoomTypes.ToList();
My code's generating this output -
My code's generating this output

You can easily do that with css. Add chkshowhide css class to your input and div and add css as per code. Your code will be as below.
<div class="col-sm-12" id="roomtypes">
#foreach(var item in ViewBag.RoomTypes)
{
<input type="checkbox" id="chk_#item.id" name="RoomTypes" value="#item.id" class="chkshowhide"/> #item.type<br />
<div class="col-sm-12 chkshowhide" id="Price_#item.id">
<input type="number" placeholder="Enter Price" id="PriceValue" />
</div>
}
</div>
css.
div.chkshowhide {
display: none;
}
input.chkshowhide:checked + br + div.chkshowhide {
display: block;
}
You can test sample here.
function saveData() {
$('input.chkshowhide:checked').each(function() {
var chkValue = $(this).val();
var divId = this.id.replace("chk", "Price");
var priceValue = $('#' + divId).find('input').val();
console.log('chkValue=' + chkValue + ", priceValue=" + priceValue);
// Write your save code here
});
}
div.chkshowhide {
display: none;
}
input.chkshowhide:checked + br + div.chkshowhide {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input type="checkbox" id="chk_1" name="RoomTypes" value="1" class="chkshowhide"> 1<br />
<div class="col-sm-12 chkshowhide" id="Price_1">
<input type="number" placeholder="Enter Price" id="PriceValue" />
</div>
<input type="checkbox" id="chk_2" name="RoomTypes" value="2" class="chkshowhide"> 2<br />
<div class="col-sm-12 chkshowhide" id="Price_2">
<input type="number" placeholder="Enter Price" id="PriceValue" />
</div>
<input type="checkbox" id="chk_3" name="RoomTypes" value="3" class="chkshowhide"> 3<br />
<div class="col-sm-12 chkshowhide" id="Price_3">
<input type="number" placeholder="Enter Price" id="PriceValue" />
</div>
<input type="button" value="Save" onclick="saveData();" />

Related

Apply to everyone with checkbox

I record meals in this way, as I show in the image:
I created the Apply to All button, which is to fill the remaining days of the month with the same data after completing the 1st of the month. For example:
I pre-pack the day 1:
By clicking the Apply to All button fill the remaining days in the same way:
Code:
<input type='button' id='elemento' value='Aplicar a Todos' />
<td bgcolor='$color' data-semana=''><font size='2px'/>
<input id='firstCB{$year}{$month}{$day}' type='checkbox' name='arrachar[$year, $month, $day][dia]' value='$year-$month-$day'>$year-$month-$day <br />
<div>
<input type='checkbox' class='checkbox' name='arrachar[$year, $month, $day][OpcaoA]' value='Peq_Almoço'>Peq. Almoço</div> <div><input ref='firstCB{$year}{$month}{$day}' min='0' oninput='this.value = Math.abs(this.value)' type='number' name='arrachar[$year, $month, $day][Qtd]' value='$marcado_pequeno_qtd' />
<br />
</div>
<div>
<input type='checkbox' class='checkbox1' name='arrachar[$year, $month, $day][opcaoB]' value='Almoço'>Almoço</div> <div><input ref='firstCB{$year}{$month}{$day}' min='0' oninput='this.value = Math.abs(this.value)' type='number' name='arrachar[$year, $month, $day][Qtd1]' value='$marcado_almoco_qtd'/>
<br />
</div>
</td>
Javascript:
$('#elemento').on('click', function(){
var inputs = [...document.querySelectorAll("[type='checkbox']")];
if(inputs == 'checked'){ // condição
$('.checkbox').prop('checked', true);
$('.checkbox1').prop('checked', true);
}
});
I wanted you to select all the checkboxes on every day as on day 1 and also fill in the inputs with the same value as day 1.
As I have the condition does not select any checkbox when clicking the Apply to all button.
I know you are using JQuery, but heres an option in vanilla JS. Talvez te servia melhor. Portugal Ale!
const dayChecks = document.querySelectorAll('.day input[type="checkbox"]');
const dayInputs = document.querySelectorAll('.day input[type="number"]');
const btn = document.querySelector('#click');
btn.addEventListener('click', () => {
dayChecks.forEach( input => { // Handles checkboxes
if(input.checked){
const elClass = input.parentElement.getAttribute('class');
const allEls = document.querySelectorAll(`.${elClass}`);
allEls.forEach( (el) => {
el.querySelector('input[type="checkbox"]').setAttribute('checked', 'checked');
});
}
});
dayInputs.forEach( input => { // Handles Inputs
if(input.value != ''){
const value = input.value;
const elClass = input.parentElement.getAttribute('class');
const allEls = document.querySelectorAll(`.${elClass}`);
allEls.forEach( (el) => {
el.querySelector('input[type="number"]').value = value;
});
}
});
});
.week {
display: flex;
flex-direction: row;
}
.day{
padding: 20px;
}
<button id='click'>Apply to All</button>
<div class="week">
<div class="day">
<h2>Primeiro Dia</h2>
<div class="peqAlmoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="almoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="jantar">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
</div>
<div class="day">
<h2>Segundo Dia</h2>
<div class="peqAlmoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="almoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="jantar">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
</div>
<div class="day">
<h2>Terçeiro Dia</h2>
<div class="peqAlmoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="almoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="jantar">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
</div>
</div>
If you want an elegant JQuery implementation try this:
$(document).ready(function(){
// used the first checkbox (input with the date class) to select each data column for entering data
// this is the column you want replicated on other columns
$('.date').change(function() {
// inactivate every other column that is not this column
$('.date').not($(this)).prop('checked', false).parents('td').removeClass('active');
// show that this is the currently selected column
$(this).parents('td').toggleClass('active');
});
// click handler for 'apply to all' button
$('#elemento').click(function() {
var checkboxstate = {}; // object to store all the checkbox state in the current column
var numberstate = {}; // object to store content of all text input in the current column
// for each input element in the active column
$.each($('.active').find('input'), function(key, element){
if($(this).prop('type') == 'checkbox') {
// collect all checkbox state
checkboxstate[element.name] = $(this).prop('checked');
} else {
// collect all input text content
numberstate[element.name] = $(this).val();
}
});
// for each checkbox or number
$.each($('.checkbox, .number'), function(key, element) {
// store these variables beforehand so you don't need to test for them in the inner each statement
// for checkboxes
var target = checkboxstate;
var type = 'checkbox';
var property = 'checked';
// for number elements
if($(this).is('.number')) {
target = numberstate;
type = 'number';
property = 'value';
}
// assign object properties to dom elements with same type and name properties as that of the object property
$.each(target, function(key_1, element_1) {
if($(element).prop('type') == type && $(element).prop('name') == key_1) {
$(element).prop(property, element_1);
}
});
});
return false;
});
});
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="index.js"></script>
<title>My test doc</title>
<style>
table {
border-collapse: collapse;
}
.active {
background-color: #00ff00;
}
input {
margin-bottom: 5px;
}
.checkbox-div {
float: left;
}
.number-div {
float: right;
margin-left: 10px;
}
</style>
</head>
<body>
<h3>welcome</h3>
<form method="GET" action="#">
<table style="border-collapse: collapse">
<tr>
<td>
<input class="date" type='checkbox' name='date' value='date'>Date
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Peq_Almoço' value='Peq_Almoço'>Peq. Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Peq_Almoço' value='' />
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Almoço' value='Almoço'>Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Almoço' value=''/>
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Lanche' value='Lanche'>Lanche
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Lanche' value=''/>
</div>
<br/>
</td>
<td>
<input class="date" type='checkbox' name='date' value='date'>Date
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Peq_Almoço' value='Peq_Almoço'>Peq. Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Peq_Almoço' value='' />
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Almoço' value='Almoço'>Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Almoço' value=''/>
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Lanche' value='Lanche'>Lanche
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Lanche' value=''/>
</div>
<br/>
</td>
</tr>
<tr>
<td>
<input class="date" type='checkbox' name='date' value='date'>Date
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Peq_Almoço' value='Peq_Almoço'>Peq. Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Peq_Almoço' value='' />
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Almoço' value='Almoço'>Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Almoço' value=''/>
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Lanche' value='Lanche'>Lanche
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Lanche' value=''/>
</div>
<br/>
</td>
</tr>
</table>
<input type='button' id='elemento' value='Aplicar a Todos' />
</form>
</body>
</html>
Also see the Fiddle sample here
Here, each column is represented by a td element. I used the first checkbox with the date class to select the column we want other columns to replicate.
Also, the checkbox and number inputs are loosed coupled - that is, a checkbox can be unchecked with the corresponding number input filled and this will still be replicated on other columns.
Three columns were used for brevity. You can create as many columns as you want and the jQuery script will still run seamlessly.
You can apply classes to each checkbox and select all checkbox on click of Apply to All button
<input type="checkbox" class="Almoco" />
$('#elemento').on('click', function(){
if(check for your condition if you need to apply check for all checkboxes)
{
$('.Almoco').prop('checked', true);
}
//Similiarily check for other checkboxes
});
Your variable inputs is a collection of inputs, therefore you have to check the state of each input in a forEach or a for loop.
Same for other inputs that you want to modify the state.
Code:
$('#elemento').on('click', function(){
var inputs = $('td > input');
inputs.each(function(index, element){
if(element.checked) {
var children = $(element).parent().find('input[type="checkbox"]');
children.each(function(i, child){
$(child).prop('checked', true);
});
}
});
});
I was able to solve the problem of applying to everyone in the following way:
$('#elemento').click(function() {
var checkedValues = Array(8).fill(false);
var textValues = Array(7).fill('');
var checkedStep = 0;
var textStep = 0;
$('tr').find('input[type="checkbox"]').each(function(index, value){
if(index < 8){
checkedValues[index] = $(this).prop("checked");
}else{
if(checkedStep == 8){
checkedStep = 0;
}
$(this).prop('checked', checkedValues[checkedStep++]);
}
});
$('tr').find('input[type="number"]').each(function(index, value){
if(index < 7){
textValues[index] = $(this).val();
}else{
if(textStep == 7){
textStep = 0;
}
$(this).val(textValues[textStep++]);
}
});
});

Input field inside a radio button not working

I tried to make the input field onclick of a radio button work and it seems like not working.
My fiddle: https://jsfiddle.net/6qoe89j2/8/
$("#ddlMth").hide();
$("input[type='radio']").change(function() {
if ($(this).val() == "delivery-yes") {
$("#ddlMth").show();
} else {
$("#ddlMth").hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="radioFrequency" onclick="myMth()" id="radioFrequency-0" value="delivery-yes" /> Yes.
<input type="radio" name="radioFrequency" id="radioFrequency-0" /> No.
<div class="controls">
<label id="ddlMth" name="ddlMth" class="car-list-step-label" for="country">Test</label>
<input id="ddlMth" name="ddlMth" type="text" placeholder="e.g £50" class="form-control car-list-input">
</div>
You cannot have same Id for multiple elements. I have changed the Id of label and Input.
You don't need jQuery, you can do it with CSS.
See below Snippet :
.controls{
display:none;
}
input[value="delivery-yes"]:checked ~ .controls {
display: block;
}
<input type="radio" name="radioFrequency" id="radioFrequency-0" value="delivery-yes" /> Yes.
<input type="radio" name="radioFrequency" id="radioFrequency-0" /> No.
<div class="controls">
<label id="ddlMthLabel" for="ddlMth" class="ddlMth car-list-step-label">Test</label>
<input id="ddlMthInput" name="ddlMth" type="text" placeholder="e.g £50" class="ddlMth form-control car-list-input">
</div>
You set 2 elements with the same id="ddlMth". id must be unique. Jquery selects only the first one then hide it. If you want to hide the label and the input, you should hide the container of them:
$("#ddlMth").hide();
$("input[type='radio']").change(function() {
if ($(this).val() == "delivery-yes") {
$("#ddlMth").show();
} else {
$("#ddlMth").hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="radio" name="radioFrequency" id="radioFrequency-0" value="delivery-yes" /> Yes.</label>
<label><input type="radio" name="radioFrequency" id="radioFrequency-0" /> No.</label>
<div class="controls" id="ddlMth">
<label name="ddlMth" class="car-list-step-label" for="country">Test</label>
<input name="ddlMth" type="text" placeholder="e.g £50" class="form-control car-list-input">
</div>

Selector is not working in jquery

Hi I've HTML code which is
<div id="testing"></div>
<input type="text" name="amount[]" id="amount_1" value="800">
<input type="text" name="date[]" id="date_1" value="12/05/2015">
<input type="text" name="notes[]" id="notes_1" value="This is test notes">
<hr />
<hr />
<hr />
<hr />
<input type="text" name="amount[]" id="amount_2" value="1500">
<input type="text" name="date[]" id="date_2" value="12/10/2015">
<input type="text" name="notes[]" id="notes_2" value="Towing amount paid Order ID 000000001">
<hr />
<hr />
<hr />
<hr />
<input type="text" name="amount[]" id="amount_3" value="1600">
<input type="text" name="date[]" id="date_3" value="12/09/2015">
<input type="text" name="notes[]" id="notes_3" value="Towing amount paid Order ID 000000002">
Now I want to search a value in my notes fields which is Towing amount paid Order ID 000000001 and I want to empty these fields and my javascript/jquery code is
$(document).ready(function() {
if($("input[name^=notes]").val().indexOf("Towing amount paid Order ID ") > -1) {
$("#testing").text('found it');
/*var current = $("input[name^=notes]");
var onePrevious = $(current).prev();
var twoPrevious = $(current).prev().prev();
current.attr('value', '');
onePrevious.attr('value', '');
twoPrevious.attr('value', '');*/
} else {
$("#testing").text('not found');
}
});
But this code is giving me not found message what is wrong in my code I've tried different selectors but didn't work for me.
You can use jQuery :contains pseudo it will find the first element that contains the required text
Ref: https://api.jquery.com/contains-selector/
Code:
if($("input[name^='notes']:contains('Towing amount paid Order ID ')")) {
$("#testing").text('found it');
} else {
$("#testing").text('not found');
}
Demo: http://jsfiddle.net/La1bq789/
This code searches only in the input which has value - This is test notes.
To look in all fields use $.each:
$(document).ready(function () {
$("input[name^='notes']").each(function () {
if ($(this).val().indexOf("Towing amount paid Order ID ") > -1) {
$("#testing").text('found it');
} else {
$("#testing").text('not found');
}
});
});
JSFiddle - http://jsfiddle.net/FakeHeal/362o548n/
Edit for clearing the fields: http://jsfiddle.net/FakeHeal/362o548n/1/
The main problem is that you checking only one element value and you need to check all elements.
I did make some changes with your code, now it's working:
$("input[name^=notes]").each(function(){
if($(this).val().indexOf("Towing amount paid Order ID ") > -1) {
$("#testing").text('found it');
/*var current = $("input[name^=notes]");
var onePrevious = $(current).prev();
var twoPrevious = $(current).prev().prev();
current.attr('value', '');
onePrevious.attr('value', '');
twoPrevious.attr('value', '');*/
} else {
$("#testing").text('not found');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="testing"></div>
<input type="text" name="amount[]" id="amount_1" value="800">
<input type="text" name="date[]" id="date_1" value="12/05/2015">
<input type="text" name="notes[]" id="notes_1" value="This is test notes">
<hr />
<hr />
<hr />
<hr />
<input type="text" name="amount[]" id="amount_2" value="1500">
<input type="text" name="date[]" id="date_2" value="12/10/2015">
<input type="text" name="notes[]" id="notes_2" value="Towing amount paid Order ID 000000001">
<hr />
<hr />
<hr />
<hr />
<input type="text" name="amount[]" id="amount_3" value="1600">
<input type="text" name="date[]" id="date_3" value="12/09/2015">
<input type="text" name="notes[]" id="notes_3" value="Towing amount paid Order ID 000000002">
$(document).ready(function() {
$("input").each(function() {
if ($(this).val().indexOf("Towing amount paid Order ID ") > -1) {
$("#testing").text('found it');
/*var current = $("input[name^=notes]");
var onePrevious = $(current).prev();
var twoPrevious = $(current).prev().prev();
current.attr('value', '');
onePrevious.attr('value', '');
twoPrevious.attr('value', '');*/
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="testing"></div>
<input type="text" name="amount[]" id="amount_1" value="800">
<input type="text" name="date[]" id="date_1" value="12/05/2015">
<input type="text" name="notes[]" id="notes_1" value="This is test notes">
<hr />
<hr />
<hr />
<hr />
<input type="text" name="amount[]" id="amount_2" value="1500">
<input type="text" name="date[]" id="date_2" value="12/10/2015">
<input type="text" name="notes[]" id="notes_2" value="Towing amount paid Order ID 000000001">
<hr />
<hr />
<hr />
<hr />
<input type="text" name="amount[]" id="amount_3" value="1600">
<input type="text" name="date[]" id="date_3" value="12/09/2015">
<input type="text" name="notes[]" id="notes_3" value="Towing amount paid Order ID 000000002">
$("input[name^=notes]").val() will only ever return the value of the first element in the page than matches that selector.
In order to check all of them you need to look at each instance
I would suggest you modularize the repeating groups by wrapping each group in a container to help locate other related elements within each group
<div class="input-group">
<input type="text" name="amount[]" id="amount_1" value="800">
<input type="text" name="date[]" id="date_1" value="12/05/2015">
<input type="text" name="notes[]" id="notes_1" value="This is test notes">
</div>
Then loop over the inputs you want to focus on
var hasNotes = $("input[name^=notes]").filter(function(){
return this.value.indexOf("Towing amount paid Order ID ") > -1
}).length;
var message = hasNotes ? 'found it' :'not found'
$('#testing.text(message);
If you need to make adjustments to other values, use an each lopp and traverse within the container

Adding Placeholder attributes base on input label with PURE JS - no jQuery

I need to get the label of each element and apply it to the input as a placeholder attribute, I get about half way though but cannot seem to get just the text of the element in order to add a attribute
Please note that i am not able to use jQuery in any regard
JS:
var elements = document.querySelectorAll('p.form-field');
Array.prototype.forEach.call(elements, function(el, i){
var chel = el.querySelectorAll('.field-label');
console.log(chel.textContent);
});
HTML:
<form accept-charset="UTF-8" method="post" action="nottelling" class="form" id="pardot-form">
<p class="form-field first_name pd-text required ">
<label class="field-label" for="25492_61334pi_25492_61334">First Name</label>
<input type="text" name="25492_61334pi_25492_61334" id="25492_61334pi_25492_61334" value="" class="text" size="30" maxlength="32" onchange="" />
</p>
<div id="error_for_25492_61334pi_25492_61334" style="display:none"></div>
<p class="form-field last_name pd-text required ">
<label class="field-label" for="25492_61336pi_25492_61336">Last Name</label>
<input type="text" name="25492_61336pi_25492_61336" id="25492_61336pi_25492_61336" value="" class="text" size="30" maxlength="32" onchange="" />
</p>
<div id="error_for_25492_61336pi_25492_61336" style="display:none"></div>
<p class="form-field email pd-text required ">
<label class="field-label" for="25492_61338pi_25492_61338">Email</label>
<input type="text" name="25492_61338pi_25492_61338" id="25492_61338pi_25492_61338" value="" class="text" size="30" maxlength="255" onchange="piAjax.auditEmailField(this, 25492, 61338, 12545572);" />
</p>
<div id="error_for_25492_61338pi_25492_61338" style="display:none"></div>
<p class="form-field company pd-text required ">
<label class="field-label" for="25492_61340pi_25492_61340">Company</label>
<input type="text" name="25492_61340pi_25492_61340" id="25492_61340pi_25492_61340" value="" class="text" size="30" maxlength="100" onchange="" />
</p>
<div id="error_for_25492_61340pi_25492_61340" style="display:none"></div>
<p style="position:absolute; width:190px; left:-9999px; top: -9999px;visibility:hidden;">
<label for="pi_extra_field">Comments</label>
<input type="text" name="pi_extra_field" id="pi_extra_field" />
</p>
<input name="_utf8" type="hidden" value="☃" />
<p class="submit">
<input type="submit" accesskey="s" value="Send Message" />
</p>
<input type="hidden" name="hiddenDependentFields" id="hiddenDependentFields" value="" />
</form>
var labels = document.querySelectorAll("label");
var i = labels.length;
while (i--) {
var label = labels.item(i);
var text = label.textContent;
label.parentNode.classList.contains("required") && (text += "*");
label.nextElementSibling.setAttribute("placeholder", text);
}
While the earlier answers work, I'd suggest a simpler approach, such as:
function placeholderLabels() {
// get <input> elements that are in a <p> and follow a <label>:
var inputs = document.querySelectorAll('p label + input');
// iterate over those <input> elements:
Array.prototype.forEach.call(inputs, function(input) {
// input is the current <input> from the NodeList over which we're
// iterating, here we set its placeholder property to either:
// the textContent of the first <label> associated with the <input>
// or to an empty string, if there's no associated <label>:
input.placeholder = input.labels.length ? input.labels[0].textContent.trim() : '';
});
}
placeholderLabels();
function placeholderLabels() {
var inputs = document.querySelectorAll('p label + input');
Array.prototype.forEach.call(inputs, function(input) {
input.placeholder = input.labels.length ? input.labels[0].textContent.trim() : '';
});
}
placeholderLabels();
label {
display: inline-block;
width: 7em;
}
p.required label::after {
content: '*';
}
<form accept-charset="UTF-8" method="post" action="nottelling" class="form" id="pardot-form">
<p class="form-field first_name pd-text required ">
<label class="field-label" for="25492_61334pi_25492_61334">First Name</label>
<input type="text" name="25492_61334pi_25492_61334" id="25492_61334pi_25492_61334" value="" class="text" size="30" maxlength="32" onchange="" />
</p>
<div id="error_for_25492_61334pi_25492_61334" style="display:none"></div>
<p class="form-field last_name pd-text required ">
<label class="field-label" for="25492_61336pi_25492_61336">Last Name</label>
<input type="text" name="25492_61336pi_25492_61336" id="25492_61336pi_25492_61336" value="" class="text" size="30" maxlength="32" onchange="" />
</p>
<div id="error_for_25492_61336pi_25492_61336" style="display:none"></div>
<p class="form-field email pd-text required ">
<label class="field-label" for="25492_61338pi_25492_61338">Email</label>
<input type="text" name="25492_61338pi_25492_61338" id="25492_61338pi_25492_61338" value="" class="text" size="30" maxlength="255" onchange="piAjax.auditEmailField(this, 25492, 61338, 12545572);" />
</p>
<div id="error_for_25492_61338pi_25492_61338" style="display:none"></div>
<p class="form-field company pd-text required ">
<label class="field-label" for="25492_61340pi_25492_61340">Company</label>
<input type="text" name="25492_61340pi_25492_61340" id="25492_61340pi_25492_61340" value="" class="text" size="30" maxlength="100" onchange="" />
</p>
<div id="error_for_25492_61340pi_25492_61340" style="display:none"></div>
<p style="position:absolute; width:190px; left:-9999px; top: -9999px;visibility:hidden;">
<label for="pi_extra_field">Comments</label>
<input type="text" name="pi_extra_field" id="pi_extra_field" />
</p>
<input name="_utf8" type="hidden" value="☃" />
<p class="submit">
<input type="submit" accesskey="s" value="Send Message" />
</p>
<input type="hidden" name="hiddenDependentFields" id="hiddenDependentFields" value="" />
</form>
It's worth reiterating at this point, however, that this is not a good user-interface; the placeholder should not replace the <label>, and if used should provide some guidance on what the <input> expects, such as the format or an expected value.
You’re close: the problem is just that you are trying to use the object returned by the second querySelectorAll as if it were an element. It returns a collection, even when there is just one matching element. If you know that only one element matches it, simply index it with a zero. The same way you can access the input element, if you know there is only one such element inside each p element. So the essential code can be as follows:
var elements = document.querySelectorAll('p.form-field');
Array.prototype.forEach.call(elements, function(el, i){
el.querySelectorAll('input')[0].placeholder =
el.querySelectorAll('.field-label')[0].textContent;
});
There are several possible approaches, depending on the assumptions you make about the source code.
Note: Duplicating label texts as placeholders is useless and disturbing. Replacing label text by placeholders is bad for accessibility and frowened upon in the HTML5 spec. But maybe the operation you are doing has some different purpose.

Combo box for all control

I created a filterable drop Down List using JavaScript. This is the List Box Coding.
<select name="d1" class="leftselect" id="d1" size="5" ondblclick="DropDownTextToBox('d1','t1');" style="display:none;" >
<option>axcsus-COMMON STOCK</option>
<option>aces</option>
<option>bdfs</option>
<option>befs</option>
<option>behs</option>
<option>dfgh</option>
<option>dhes</option>
<option>dwww</option>
<option>pass</option>
<option>pass</option>
</select>
I created 4 Text Field and a arrow character. If i click the arrow character , I'll show the list at the bottom of the control.
<div id="div_name" style="float:left;z-index: 20;">
<input name="t1" type="text" id="t1" onkeyup="value_filtering('d1','t1');" onkeypress="onEnter(event,'d1','t1')" />
<input type="button" class="rightselect" onclick="displayList('d1','t1');" value="▼" />
</div>
<div class="inputbox">
<input name="t2" class="inputbox" type="text" id="t2" onkeyup="value_filtering('d2','t2');" onkeypress="onEnter(event,'d2','t2')" />
<input type="button" class="leftselect" onclick="displayList('d1','t2');" value="▼" />
</div>
<div style="float:left;text-align:center;" >
<input name="t3" type="text" id="t3" onkeyup="value_filtering('d3','t3');" onkeypress="onEnter(event,'d3','t3')" />
<input type="button" class="rightselect" onclick="displayList('d1','t3');" value="▼" />
</div>
<div class="inputbox">
<input name="t4" class="inputbox" type="text" id="t4" onkeyup="value_filtering('d4','t4');" onkeypress="onEnter(event,'d4','t4')" />
<input type="button" class="leftselect" onclick="displayList('d1','t4');" value="▼" />
</div>
In the display List function I'm getting the corresponded textbox position and displayed the List Control under the Text Box. Okie. Now my problem is If i select any option in the text box, I need to display the selected value to the textbox which the listbox shown under. After selecting the value from the list box, How i find in which text box showing the List ? Dynamically how can i find the text box id ?
This is my JS code for displaying the Listbox to the corresponding TextBox.
function displayList(ele,txt)
{
vis=document.getElementById(ele);
obj=document.getElementById(txt);
if (vis.style.display==="none")
vis.style.display="block";
else
vis.style.display="none";
vis.style.position = "absolute";
//alert(getElementPosition(txt).top + ' ' + getElementPosition(txt).left);
vis.style.top = getElementPosition(txt).top+obj.offsetHeight;
vis.style.left = getElementPosition(txt).left;
}
Note : I can call this function at the click event of arrow button. I can easily pass the text Field Id. But in the case ListBox action i can't send the particular ID of the Text Field.
If you have no opposition to using jquery you can using the jquery UI built-in autocomplete which will do pretty much what you're looking for. For more advanced and nicer plugins you can try chosen
Try this.
<script>
var targetInput=null;
function displayList(ele,txt) {
vis=document.getElementById(ele);
obj=document.getElementById(txt);
targetInput = obj;
if (vis.style.display==="none") {
vis.style.display = "block";
} else {
vis.style.display = "none";
vis.style.position = "absolute";
//alert(getElementPosition(txt).top + ' ' + getElementPosition(txt).left);
vis.style.top = getElementPosition(txt).top+obj.offsetHeight;
vis.style.left = getElementPosition(txt).left;
}
}
function selectList(txt) {
if (!targetInput) return;
targetInput.value = txt.value;
txt.style.display = 'none';
}
</script>
<div id="div_name" style="float:left;z-index: 20;">
<input name="t1" type="text" id="t1" onkeyup="value_filtering('d1','t1');" onkeypress="onEnter(event,'d1','t1')" />
<input type="button" class="rightselect" onclick="displayList('d1','t1');" value="▼" />
</div>
<div class="inputbox">
<input name="t2" class="inputbox" type="text" id="t2" onkeyup="value_filtering('d2','t2');" onkeypress="onEnter(event,'d2','t2')" />
<input type="button" class="leftselect" onclick="displayList('d1','t2');" value="▼" />
</div>
<div style="float:left;text-align:center;" >
<input name="t3" type="text" id="t3" onkeyup="value_filtering('d3','t3');" onkeypress="onEnter(event,'d3','t3')" />
<input type="button" class="rightselect" onclick="displayList('d1','t3');" value="▼" />
</div>
<div class="inputbox">
<input name="t4" class="inputbox" type="text" id="t4" onkeyup="value_filtering('d4','t4');" onkeypress="onEnter(event,'d4','t4')" />
<input type="button" class="leftselect" onclick="displayList('d1','t4');" value="▼" />
</div>
<select name="d1" class="leftselect" id="d1" size="5" ondblclick="DropDownTextToBox('d1','t1');" onclick="selectList(this)" style="display:none;">
<option>axcsus-COMMON STOCK</option>
<option>aces</option>
<option>bdfs</option>
<option>befs</option>
<option>behs</option>
<option>dfgh</option>
<option>dhes</option>
<option>dwww</option>
<option>pass</option>
<option>pass</option>
</select>

Categories