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);
`
Related
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 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.
This question already has an answer here:
Cannot get link to be clicked and switch to next page using PhantomJS
(1 answer)
Closed 7 years ago.
I am attempting to automate a website on my remote server using PhantomJS.
For this website I have to log in with my username and password.
Examining the HTML, I see:
<form class="" method="post" action="https://foo.com/login/"
id="foo_login_bar" accept-charset="utf-8">
<input tabindex="1" name="user_name" id="user" value="" type="text">
<input tabindex="2" name="password" id="pass" value="" type="password">
<div class="wrapper_login_button">
<input class="saved_url_for_login" name="login_url"
value="http://foo.com/" type="hidden">
<input tabindex="3" id="login_button" class="btn left login_button"
name="login" value="Login" type="submit">
</div>
</form>
So I try:
var page = require('webpage').create();
page.onConsoleMessage = function(msg) {
console.log('CONSOLE: ' + msg);
};
page.open('http://foo.com', function(status)
{
console.log("Status: " + status);
if(status === "success")
page.evaluate( bot );
page.render('example.png');
phantom.exit();
});
function bot()
{
if( ! Foo.isLoggedIn() ) {
console.log("Not logged in!");
document.getElementById( "user" ).value = "myuser";
document.getElementById( "pass" ).value = "mypass";
document.getElementById( "login_button" ).click();
}
}
Examining the screenshot shows that it has correctly entered text into the user and password fields, but it has failed to refresh the page.
i.e. If I fill out both fields and click the login button on Firefox, it takes me to my account homepage.
I'm guessing that what is happening here is that the code is immediately reaching the screenshot before the page has had a chance to reload.
How can I get execution to continue once the reload has completed?
EDIT: Phantomjs login, redirect and render page after pageLoad finishes
I'm guessing that what is happening here is that the code is immediately reaching the screenshot before the page has had a chance to reload.
You are absolutely right, you need to wait for the page to reload.
In PhantomJS you can register callback functions for when a page is done loading.
var page = require('webpage').create();
var action;
page.onLoadFinished = function(result)
{
page.render('example' + (new Date()).getTime() + '.png');
// Need to check `action` variable because
// this callback will also fire when opening page for the first time
if(action == "loggin in")
{
phantom.exit();
}
}
page.onConsoleMessage = function(msg) {
console.log('CONSOLE: ' + msg);
};
page.open('http://foo.com', function(status)
{
console.log("Status: " + status);
if(status === "success")
{
action = "loggin in";
page.evaluate( bot );
}
});
function bot()
{
if( ! Foo.isLoggedIn() )
{
console.log("Not logged in!");
document.getElementById( "user" ).value = "myuser";
document.getElementById( "pass" ).value = "mypass";
document.getElementById( "login_button" ).click();
}
}
I'm trying to upload files using dropzone.js
View:
#using (Html.BeginForm("SaveMethod", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data", #class = "dropzone", id = "js-upload-form" }))
........................
<div class="form-inline">
<div class="form-group">
<input type="file" name="MainFile" id="js-upload-files"/>
</div>
<div class="upload-drop-zone" id="drop-zone">
Just drag and drop files here
</div>
<div class="dropzone-previews"></div>
</div>
JS:
var formData = null;
formData = new FormData($form[0]);
dropZone.ondrop = function (e) {
e.preventDefault();
this.className = 'upload-drop-zone';
startUpload(e.dataTransfer.files)
}
dropZone.ondragover = function () {
this.className = 'upload-drop-zone drop';
return false;
}
dropZone.ondragleave = function () {
this.className = 'upload-drop-zone';
return false;
}
var startUpload = function (files) {
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
}
Controller:
[HttpPost]
public JsonResult SaveMethod(TaskManage objTaskManage, HttpPostedFileBase files)
{
}
Now, after submit, i want to have files that was dropped on drop area along with the files attached in upload control. Here, what happens is files giving me null and when i use Request.Files["MainFile"] i get only the files dropped on dropzone area, it doesn't show me the file i have upload to control.
I'm not able to find out the issue. Any help is really appreciated.
File upload in ASP.NET MVC using Dropzone JS and HTML5
You can download the latest version from the official site here http://www.dropzonejs.com/ and also we can install using the nuget package manage console by the following command Package Manager Console
PM> Install-Package dropzone
Now create a bundle for your script file in BundleConfig.cs
bundles.Add(new ScriptBundle("~/bundles/dropzonescripts").Include(
"~/Scripts/dropzone/dropzone.js"));
Similarly add the dropzone stylesheet in the BundleConfig.cs
bundles.Add(new StyleBundle("~/Content/dropzonescss").Include(
"~/Scripts/dropzone/css/basic.css",
"~/Scripts/dropzone/css/dropzone.css"));
Now add the bundle reference in your _Layout page
View Page:
<div class="jumbotron">
<form action="~/Home/SaveUploadedFile" method="post" enctype="multipart/form-data" class="dropzone" id="dropzoneForm" style="width: 50px; background: none; border: none;">
<div class="fallback">
<input name="file" type="file" multiple />
<input type="submit" value="Upload" />
</div>
</form>
</div>
Controller:
public ActionResult SaveUploadedFile()
{
bool isSavedSuccessfully = true;
string fName = "";
try{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//Save file content goes here
fName = file.FileName;
if (file != null && file.ContentLength > 0)
{
var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(#"\")));
string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath");
var fileName1 = Path.GetFileName(file.FileName);
bool isExists = System.IO.Directory.Exists(pathString);
if (!isExists)
System.IO.Directory.CreateDirectory(pathString);
var path = string.Format("{0}\\{1}", pathString, file.FileName);
file.SaveAs(path);
}
}
}
catch(Exception ex)
{
isSavedSuccessfully = false;
}
if (isSavedSuccessfully)
{
return Json(new { Message = fName });
}
else
{
return Json(new { Message = "Error in saving file" });
}
}
Now add the following script to your view page at the and in script tag.
//File Upload response from the server
Dropzone.options.dropzoneForm = {
init: function () {
this.on("complete", function (data) {
//var res = eval('(' + data.xhr.responseText + ')');
var res = JSON.parse(data.xhr.responseText);
});
}
};
Here you can see the response from server.
Good morning everyone. I tried creating a site that could get information from another page and feed the response into a div tag, but it didnt work. I checked with a very similar one i learnt from. Here is the HTML code.
<html>
<head>
<script>
function checkit(){
var samxml; var username;
if (window.XMLHttpRequest){
samxml = new XMLHttpRequest();}
else {
samxml = new ActiveXObject("Microsoft.XMLHTTP");
}
samxml.onreadystatechange = function() {
if (samxml.readyState == 4 && samxml.status == 200){
document.getElementById("check").innerHTML = samxml.responseText;}
}
username = document.getElementById("username").value;
samxml.open("POST", "check.php",true);
samxml.send( "username" );
}
}
</script>
</head>
<body>
<form>
<label for ="username">User ID:</label>
<input type = "text" name = "username" id = "username"/>
<div id = "check"></div>
<button type = "button" onclick = "checkit()">Check</button>
</form>
</body>
</html>
Here is the PHP page:
//php file
<?php
$user = $_POST["username"];
if ($user == "samuel") {
echo "Hmm. Chosen! Choose another one";}
else {
echo "Nice one";}
?>
Thanks so much.