I want get all my input and select elements off my page HTML. I've tried getElementsByTagName('input,select') but it does not work.
My code HTML and JavaScript:
function myFunction() {
var data = [];
var data1 = [];
var data2 = [];
for (var i = 0; i < 10; ++i) {
var x = document.getElementsByTagName("INPUT,SELECT")[i].getAttribute("name");
var y = document.getElementsByTagName("INPUT,SELECT")[i].getAttribute("type");
var z = document.getElementsByTagName("INPUT,SELECT")[i].getAttribute("maxlength");
data.push(x);
data1.push(y);
data2.push(z);
location.href ="ttt.php?name=" + data + "&active=" + data1 + "&data2=" + data2
}
}
<select name="CIV"><option selected="selected" value=""></option><option selected="selected" value="">Mr</option><option selected="selected" value="">Mme</option></select>
<input type="text" size="20" name="first_name" id="first_name" maxlength="50" class="cust_form" value="">
<input type="text" size="20" name="last_name" id="last_name" maxlength="50" class="cust_form" value="">
<input type="text" size="20" name="address3" id="address3" maxlength="50" class="cust_form" value="">
You should access the elements separately; INPUT and SELECT. BTW, Select element doesn't have type and maxlength attributes.
function myFunction() {
var nameData = [];
var typeData = [];
var maxLengthData = [];
var input = document.getElementsByTagName("INPUT")
var select = document.getElementsByTagName("SELECT")
// Targeting the first 9 of elements of input collections and select collections
// Assuming you understand what you are doing here
for (var i = 0; i < 10; ++i) {
nameData.push( input[i].getAttribute( 'name' ) );
nameData.push( select[i].getAttribute( 'name' ) );
typeData.push( input[i].getAttribute( 'type' ) ); // Select element doesn't have type attribute
maxLengthData.push( inputt[i].getAttribute( 'maxlength' ) ); // Select elemnt doesn't have maxlength attribute
// Assuming you understand what you are doing to build your url here
location.href ="ttt.php?name=" + nameData + "&active=" + typeData + "&data2=" + maxLengthData
}
}
Please, read more on HTML elements and their attributes. Also, read more on pure JavaScript.
Note: this has not been tested yet. Try it and let me know if it does what you you want it to do.
Related
I am trying to perform credit card validator i.e adding space after every fourth digit like 1111 1111 1111 1111. But somehow I can't get work done.
Here is what I have tried.
Thank you in advance
html
<ion-item>
<ion-label position="floating">Card number</ion-label>
<ion-input type ="tel" formControlName = "cardnumber" keypress ="cc_format($evet)" ></ion-input>
</ion-item>
ts
cc_format(value) {
var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
var matches = v.match(/\d{4,16}/g);
var match = matches && matches[0] || ''
var parts = []
for (let i=0, len=match.length; i<len; i+=4) {
parts.push(match.substring(i, i+4))
}
if (parts.length > 0) {
return parts.join(' ')
} else {
return value
}
}
First let's use ionChange to get the changed value from your input. Connect your input with the creditCardNumber defined in the ts file. Now convert the credit card number and add it to the dynamic variable.
<ion-item>
<ion-label position="floating">Card number</ion-label>
<ion-input type ="tel" formControlName="cardnumber" (ionChange)="cc_format($event.target.value)" [(ngModel)]="creditCardNumber"></ion-input>
</ion-item>
creditCardNumber: string;
cc_format(value: string) {
const v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '');
const matches = v.match(/\d{4,16}/g);
const match = (matches && matches[0]) || '';
const parts = [];
for (let i = 0, len = match.length; i < len; i += 4) {
parts.push(match.substring(i, i + 4));
}
if (parts.length > 0) {
this.creditCardNumber = parts.join(' ');
} else {
this.creditCardNumber = value;
}
}
I have a dynamically generated component which generates on run time. following is the .ts file
`#ViewChild(TermsheetDirective) termHost: TermsheetDirective;
#Input() term;
#Input() title = '';
#Input() Qnumber = '';
#Output() result = new EventEmitter<any>();
section_title = '';
number = '';
component = [];
show = false;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
}
ngOnInit() {
this.number = this.Qnumber;
this.section_title = this.title;
}
ngAfterViewInit() {
}
ngAfterContentInit() {
}
loadcomponents() {
console.log(this.termHost);
for (let j = 0; j < this.term.components.length; j++) {
let termItem = this.term.components[j];
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(termItem.component);
let viewContainerRef = this.termHost.viewContainerRef;
let componentRef = viewContainerRef.createComponent(componentFactory);
(<TermComponent>componentRef.instance).data = termItem.data;
this.component[j] = componentRef;
}
}
getdata() {
let output = [];
for (let i = 0; i < this.component.length; i++) {
let temp = {
slug : this.section_title,
type : this.component[i].type,
value : this.component[i]._component.getdata()
};
output[i] = temp;
}
this.result.emit(output);
return output;
}
showcomp() {
console.log("In if");
this.show = true;
this.loadcomponents();
}
hidecomp() {
this.show = false;
}`
and following is my html
`<div class="main">
<div class="div_for_ques">
<div class="question">
<div class="number">
{{number}}
</div>
<div class="textbox">
{{section_title}}
</div>
<div class="arrow" *ngIf="!show">
<a (click)="showcomp()" class="glyphicon"></a>
</div>
<div class="arrow" *ngIf="show">
<a (click)="hidecomp()" class="glyphicon"></a>
</div>
</div>
<div class="sec_two" *ngIf="show">
<ng-template term-host></ng-template>
</div>
</div>
</div>`
I want the div that contains the dynamically generated component to appear only when a certain button is clicked. but i am having following response.
But when I try to show this div without ngIf it is working fine. But with ngIf termHost is undefined! Can someone please explain what is happening here!
Well, you are trying to reference to viewContainerRef before change detection cycle has completed, that is why you get that error.
There is more than one solution to this, you can use a setter for the ViewChild, that will be called once after the *ngIf becomes true
e.g
#ViewChild('') set content(x:x) {
this.x = x;
}
OR you can inject the change detector manually
constructor(private changeDetector : ChangeDetectorRef) {}
You can then call it after you click your button
this.changeDetector.detectChanges();
OR You can also use a QueryList to achieve the same effect because you can subscribe to changes
Please apply these techniques to your logic to solve your problem
I need a data set of location points (Lat. and Lon.) is there any tool I can use where I can draw the path on a map and get the points as required format? Or is there any other easy way to do this? Thanks in Advance.
I have found a solution check it out, and make sure add the external Jar and CSS resorses.
The HTML
<div id="map" style="width: 800px; height:500px" align="center"></div>
<br>
<button type="button" onclick="getAllLocations();">GET ALL THE LOCATIONS</button>
<div>
<h3>Output Console</h3>
<textarea id="TextArea" rows="8" cols="80"></textarea>
<br>
The JS
var map = L.map('map').setView([ 6.88869, 79.85878 ], 18);
L.tileLayer(
'https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png',
{
maxZoom : 20,
attribution : 'Map data © OpenStreetMap contributors, '
+ 'CC-BY-SA, '
+ 'Imagery © Mapbox',
id : 'examples.map-i86knfo3'
}).addTo(map);
var poly = L.polyline([], {
color : 'green'
});
poly.addTo(map);
map.on('click', function(e) {
poly.addLatLng(e.latlng);
//alert();
});
getAllLocations = function (){
alert ("Test");
var locArray = poly.getLatLngs();
var area = document.getElementById('TextArea');
for(var i=0; i<locArray.length; i++){
var item2 = locArray[i];
var item3 = "" + item2;
var item4 = item3.split("(");
var item5 = item4[1].split(")")
//alert(item5[0]);
area.value += item5[0] + "\n";
}
}
http://jsfiddle.net/ZdLrb/13/
I'm using this
auto-complete plugin with my new project. It's working fine. See image
But I want to populate these fields when I select the result.
Here is my code:
var as = $("#query" + x + "").autocomplete({
minChars: 1,
maxHeight: 100,
serviceUrl: 'index.php?r=purchaseorder/list',
});
IN CONTROLLER
public function actionList() {
$criteria = new CDbCriteria;
$criteria->select = array('id','description','unit','rate');
$criteria->addSearchCondition("description", $_GET['query']);
$criteria->limit = $this->limit;
$items = Item::model()->findAll($criteria);
$suggestions = array();
$data = array();
foreach ($items as $c) {
$suggestions[] = $c->description;
$data[] = $c->id;
}
header('Content-type: application/json; charset=utf-8');
echo CJSON::encode(
array(
'query' => 'q',
'suggestions' => $suggestions,
'data' => $data
)
);
exit;
}
grid jquery
jQuery("#addrow").click(function() {
jQuery(".item-row:last").after('<tr class="item-row">\n\
<td>\n\
<span id="delete' + x + '" style="cursor: pointer" class="icon-remove"></span>\n\
</td>\n\
<td class="item-code"><input autocomplete="off" name="code[]" id="code' + x + '" type="text" class="input-code"/></td>\n\
<td class="item-description"><input autocomplete="off" name="q" id="query' + x + '" type="text" class="input-description"/></td>\n\
<td class="item-unit"><input readonly autocomplete="off" name="unit[]" id="unit' + x + '" type="text" class="input-unit"/></td>\n\
<td class="item-qty"><input name="qty[]" autocomplete="off" value="0" id="qty' + x + '" type="text" class="input-qty"/></td>\n\
<td class="item-rate"><input readonly name="rate[]" autocomplete="off" value="125.25" id="rate' + x + '" type="text" class="input-rate"/></td>\n\
<td class="item-discount"><input name="discount[]" autocomplete="off" value="0.00" id="discount' + x + '" type="text" class="input-discount"/></td>\n\
<td class="item-total"><input name="total[]" readonly autocomplete="off" value="0.00" id="total' + x + '" type="text" class="input-amount"/></td>\n\
</tr>');
controller is already there
I have done it like this...
IN JQUERY....
var as = $("#query").autocomplete({
minChars: 1,
maxHeight: 100,
serviceUrl: 'index.php?r=purchaseorder/list',
onSelect: function(suggestion) {
var row = $(this).closest('tr');
row.find('.input-code').val(suggestion.id).attr('readonly', 'readonly');
row.find('.input-description').attr('readonly', 'readonly');
row.find('.input-unit').val(suggestion.unit).attr('readonly', 'readonly');
row.find('.input-rate').val(suggestion.rate).attr('readonly', 'readonly');
row.find('.input-qty').focus();
}
});
AND THEN IN CONTROLLER
public function actionList() {
$criteria = new CDbCriteria;
$criteria->select = array('description', 'id','unit','rate');
$criteria->addSearchCondition("description", $_GET['query']);
$criteria->limit = $this->limit;
$items = Item::model()->findAll($criteria);
$suggestions = array();
$x=0;
foreach ($items as $c) {
$suggestions[$x]['value'] = $c->description;
$suggestions[$x]['id'] = $c->id;
$suggestions[$x]['rate'] = $c->rate;
$suggestions[$x]['unit'] = $c->unit;
$x++;
}
header('Content-type: application/json; charset=utf-8');
echo CJSON::encode(
array(
'suggestions' => $suggestions,
)
);
exit;
}
thats it...!
Sample code as shown below
$('#yourautoCompleteId').change(function(){
var selecteddata=$(this).val();
$.ajax({
url: "'.$this->createUrl('Controller/yourMethod').'",
data: {
//special:specialisation,
data :selecteddata,
},
type:"GET",//you can also use POST method
dataType:"html",//you can also specify for the result for json or xml
success:function(response){
//write the logic to get the response data as u need and set it to the fields
$("#dataId").val("SetHere");
$('#quantityId').val("setHere");
},
error:function(){
//TODO: Display in the poll tr ifself on error
alert("Failed request data from ajax page");
}
});
})
get the data in the controller using post and query with this data and send the result as u need and set to the fields as shown in the sample
i'm aiming to put 2 search forms on the same wordpress page. i'm using the iframe form code and have already sorted out how to direct that to a search element.
but the form includes the following script:
www.google.com/cse/brand?form=cse-search-box&lang=en
which starts by defining the search box by ID
var f = document.getElementById('cse-search-box');
but if you use multiple forms then you (incorrectly i know) end up with elements that have the same ID.. and the branding+ focus/blur events don't work across both forms.
the form basically looks like:
<form action="/search.php" class="cse-search-box">
<div>
<input type="hidden" name="cx" value="" />
<input type="hidden" name="cof" value="FORID:10" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" size="32" />
<input type="submit" name="sa" value="Search" />
</div>
</form>
<script type="text/javascript" src="//www.google.com/cse/brand?form=cse-search-box&lang=en"></script>
if this were a jquery script i think it'd be easy to change the ID to a class name and do an .each() iteration. but google's code is pure javascript and i'm not familiar with that, though
i read getElementbyClass isn't super reliable.
so is this fixable or not worth worrying over?
eventually i commented out that script from google.com and replaced it w/ my own custom version:
`
if (window.history.navigationMode) {
window.history.navigationMode = 'compatible';
}
jQuery.noConflict();
jQuery(document).ready(function($) { //tells WP to recognize the $ variable
//from google's original code- gets the URL of the current page
var v = document.location.toString();
var existingSiteurl = /(?:[?&]siteurl=)([^&#]*)/.exec(v);
if (existingSiteurl) {
v = decodeURI(existingSiteurl[1]);
}
var delimIndex = v.indexOf('://');
if (delimIndex >= 0) {
v = v.substring(delimIndex + '://'.length, v.length);
}
$(".cse-search-box").each( function() {
var q = $(this).find("input[name=q]");
var bg = "#fff url(http:\x2F\x2Fwww.google.com\x2Fcse\x2Fintl\x2Fen\x2Fimages\x2Fgoogle_custom_search_watermark.gif) left no-repeat";
var b = "#fff";
if (q.val()==""){
q.css("background",bg);
} else {
q.css("background",b);
}
q.focus(function() {
$(this).css("background", b);
});
q.blur(function() {
if($(this).val()==""){
$(this).css("background", bg);
}
});
//adds hidden input with site url
hidden = '<input name="siteurl" type="hidden" value="'+ v +'">'
$(this).append(hidden);
});
}); //end document ready functions
`
and on the search.php page that you are directing the results to (so this is a 2-page search form, i found a tutorial on that online somewhere) you will need:
`
google.load('search', '1', {language : 'en', style : google.loader.themes.MINIMALIST});
/**
* Extracts the users query from the URL.
*/
function getQuery() {
var url = '' + window.location;
var queryStart = url.indexOf('?') + 1;
if (queryStart > 0) {
var parts = url.substr(queryStart).split('&');
for (var i = 0; i < parts.length; i++) {
if (parts[i].length > 2 && parts[i].substr(0, 2) == 'q=') {
return decodeURIComponent(
parts[i].split('=')[1].replace(/\+/g, ' '));
}
}
}
return '';
}
function onLoad() {
// Create a custom search control that uses a CSE restricted to
// code.google.com
var customSearchControl = new google.search.CustomSearchControl)('google_search_id');
var drawOptions = new google.search.DrawOptions();
drawOptions.setAutoComplete(true);
// Draw the control in content div
customSearchControl.draw('results', drawOptions);
// Run a query
customSearchControl.execute(getQuery());
}
google.setOnLoadCallback(onLoad);
`