Get Attribute Values From Child Element With No ID - JQuery - attributes

Lets say I have this code:
<div id="Element_1" class="draggable">
<input type="text" placeholder="Enter Your Text Here" style="width:300px;">
</div>
<div id="Element_2" class="draggable">
<textarea placeholder="Enter Your Text Here" style="width:400px;height:200px;"></textarea>
</div>
What I am trying to do is get the element attribute values, from the child of the "div" and also the "Type" (Input/Tagname) so I can store the values in variables.
Currently I can get the element and store in a Var, this is the code I have:
$(".draggable").live("click",function(){
var SelectedID = $(this).attr("id");
$("*").removeClass("selected");
var Element = $("#"+SelectedID,":first-child").addClass("selected").html();
PlaceholderPropValue = $(element).attr("placeholder");
StylesPropValue = $(element).attr("style");
WidthProp = StylesProp.match(/(width:)([0-9].*?)(?=px;)/)[2];
HeightProp = StylesProp.match(/(height:)([0-9].*?)(?=px;)/)[2];
alert(PlaceholderPropValue+ " " +WidthProp+ " " +HeightProp);
});
Thanks!
Carl

Your code is kind of overkill.
.live() is deprecated in jQuery 1.7 and totally removed in 1.9, jquery documentation says you should use .on() instead.
Everything is simple. You can try something like:
$('.draggable').click(function(){
var $element = $(this).children();
var width = parseInt($element.width());
var height = parseInt($element.height());
var placeholder = $element.attr('placeholder');
alert(placeholder+ " " +width+ " " +height);
})
.children() method normally return set of element's children but there are only one in your example, so it's ok.
.width() and .height() returns values like "300px", so we use parseInt() to make int values.
.click(handler) is a shortcut for .on( "click", handler )

Related

Cheerio's first().text() returns empty value when applied on an HTML input tag with id [duplicate]

I have a HTML table that looks like this:
<tr class="row-class" role="row">
<td>Text1</td>
<td>
<form method='get' action='http://example.php'>
<input type='hidden' name='id_num' value='ABCD123'> <!-- < I NEED THIS VALUE -->
<button type='submit' class='btn' title='Check' ></button>
</form>
</td>
</tr>
I want to get the value of the hidden input type named id_num. (In this example the value I want is "ABCD123").
I tried to parse the code with cheerio like this:
var $ = cheerio.load(body);
$('tr').each(function(i, tr){
var children = $(this).children();
var x = children.eq(0);
var id_num = children.eq(1);
var row = {
"x": x.text().trim(), //this is correct, value is Text1
"id_num": id_num.text().trim() //This is empty, value is "", I want the value "ABCD123"
};
});
But I only get the first value correct.
How can I get the value from the hidden input element id_num?
Thanks.
That should be:
$(tr).find('[name="id_num"]').attr('value')
Your eq(1) was getting the whole <tr>, try this instead:
$('tr').each(function(i, tr){
var children = $(this).children('td');
var x = $(children[0]);
var id_num = $(children[1]).find("input[name='id_num']");
var row = {
"x": x.text(),
"id_num": id_num.val()
};
}

Need to pass search query into URL string using custom params

I have a simple search form that looks like this:
<form action="http://www.theurltosearch.com" method="post">
<input class="search-box" name="query" type="text" value="search all reports" />
<input type="submit" name="search" />
</form>
What I'm trying to accomplish
The search is pointing to whats really a filtering system using tags.
In order for the user to properly see the results of what they queried the query url has to look something like this http://www.theurltosearch.com/#/Kboxes the # and the K are important as its how the tagging system returns results where K stands for keyword.
For multi term queries the url has to look like this separated by a comma http://www.theurltosearch.com/#/Kboxes,Kmoving
A user should also get results when they enter a string query something like http://www.theurltosearch.com/#/K%22more%20stuff%22
Right now if someone used the search it would just take them to the url and not actually display any results matching their query.
How can I manipulate the url string to return the results how I've shown above?
My actual attempt
<script type="text/javascript">
window.onload = function(){
var form = document.getElementById("reports-search");
form.onsubmit = function(){
var searchText = document.getElementById("search-reports");
window.location = "http://www.urltosearch.com/#/K" + searchText.value;
return false;
};
};
</script>
<form id="reports-search" method="get">
<input class="search-box" id="search-reports" type="text" value="search all reports" /><!--search term was analysis-->
<input type="submit" name="search" />
</form>
returns
http://www.urltosearch.com/#/Kanalysis
and displays all results with the analysis tag
This attempt works succesfully if someone is searching a single keyword but not if the user is searching multiple or a string
How do I change the JS to achieve the other options?
Okay, here's a dog'n'bird implementation (ruff,ruff, cheap,cheap).
I've allowed the user to enter multiple terms, each separated with the pipe character | If you wish to allow the user to enter a url in essentially the same format as they'd receive by 'normal' keywords, you may wish to check the entered text first and if found, simply pass it straight through without changing it.
You'll notice, I've wrapped all search terms with " ", regardless of whether the term is multi-word or not. You could easily differentiate between a single-word term and a multi, by searching the string for a space character after the string.trim has removed leading/trailing spaces. I.e
if (trimmedTerm.indexOf(' ') == -1)
{
// single word search term
}
else
{
// multi-word search term here
}
Anyway, here's a working demo, hope it gives insight.
function byId(id){return document.getElementById(id)}
// useful for HtmlCollection, NodeList, String types
function forEach(array, callback, scope){for (var i=0,n=array.length; i<n; i++)callback.call(scope, array[i], i, array);} // passes back stuff we need
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
byId('goBtn').addEventListener('click', onGoBtnClicked);
}
function onGoBtnClicked(evt)
{
// get the user input
var inputString = byId('userInput').value;
// split it into an array of terms, based on the | char
var searchTerms = inputString.split('|');
// init the result
var result ='';
// for each element in the array of search terms, call the function to trim wrap with "" and encode
forEach(searchTerms, addCurTermToResult);
// update the output display
byId('output').textContent = 'http://www.theurltosearch.com/#/' + result;
function addCurTermToResult(curTerm, index)
{
if (index != 0) // put a comma before all terms except the first one
result += ',';
var trimmedTerm = curTerm.trim(); // remove leading/trailing spaces
result += 'K' + encodeURI('"' + trimmedTerm + '"' ); // wrap with "" then URI encode it, suitable for use as a URL
}
}
.panel
{
border: solid 1px black;
border-radius: 8px;
padding: 8px;
background-color: #eef;
display:inline-block;
}
.panel textarea
{
width: 500px;
height: 200px;
}
<div class='panel'>
<textarea type='text' id='userInput' placeholder='Enter tags or a url. tags should be seperated with the | character'></textarea>
<div style='text-align: center'><button id='goBtn'>Submit</button></div>
<hr>
<label>URL: <span id='output'></span></label>
</div>

How to get the value of Liferay input editor in a javascript variable

In my application i am using liferay-ui:input-editor .I want to get the value of input editor to a javascript variable, How to achieve that?? I have tried
<liferay-ui:input-editor />
<input name="<portlet:namespace />htmlCodeFromEditorPlacedHere" type="hidden" value="" />
function createPopUp(){
var url ="<%=fetchCandidateByIdForPhoneURL%>";
var type= "fetchCandidateInfo";
var candidateId = $('#candidateID').val();
var jobId = $('#JobList').val();
var text1 = $('#text1').val();
var text2 = $('#text2').val();
var text3 = $('#text3').val();
var interviewVenue = $('#interviewVenue').val();
var interviewCC = $('#interviewCC').val();
var interviewBCC =$('#interviewBCC').val();
var startDate = $('#start-date').val();
var interviewType = $('#interviewType').val();
var x ;
function <portlet:namespace />initEditor() {
return '<font style="font-weight: bold">scott was here</font>';
}
function <portlet:namespace />extractCodeFromEditor() {
var x = document.<portlet:namespace />fm.<portlet:namespace />htmlCodeFromEditorPlacedHere.value = window.<portlet:namespace />editor.getHTML();
alert(x);
}
But it is showing that
ReferenceError: _InterviewSchedule_WAR_InterviewScheduleportlet_initEditor is not defined error. How to resolve it and get the value in a javascript variable
Given the information provided in question, it seems that the javascript initialization function is missing for <liferay-ui:input-editor />. As pointed out in the tutorial here, which OP seems to be using (juding by variable names):
By default, the editor will call "initEditor()" to try and pre-populate the body of the editor. In this example, when the editor loads, it will have the value of "scott was here" in bold.
(...)
function <portlet:namespace />initEditor() {
return '<font style="font-weight: bold">scott was here</font>';
}
By default, the ck editor that Liferay uses will try to call the initEditor() javascript method to try and pre-populate the contents of the editor.
Therefore, you should define such a method, even if you return a blank string.
An example is given below:
<aui:script>
function <portlet:namespace />initEditor() {
return "<%= content %>";
}
</aui:script>
, where content is the string variable with the content you want to pass in when the editor is loaded. If you do not want to pass initial content then simply pass a black string.

ASP.NET MVC - What is the best way to build a search form that works properly with SEO and users without JS?

I'm working on building a search engine in my application, and because I don't want to have a Querystring in my URL, I'm currently using Javascript to submit the searchTerms for me.
Basically I am NOT using a "form", but rather just an input
<input id="searchBox" class="search" name="searchTerm" tabindex="1" onfocus=" this.className = 'search-alt'; if (this.value=='search...') this.value = ''" type="text" onkeypress="searchKeyPress(event,this.form)" maxlength="80" size="28" value="search...">
<script type="text/javascript">
function searchKeyPress(e, form) {
var key = e.keyCode || e.which;
if (key == 13) {window.location.href = '<%: url.Content("~/search") %>/' + $('#searchBox').val();}}
</script>
The problem with this method is "two fold"
If the user doesn't have Javascript, the form will not submit
I'm not sure if a search engine will be able to use this search form either
So my question is
Can I use a Form element on my page that can submit " http://example.com/search/{searchTerms} " instead of " http://example.com/search/?q={searchTerms} " while NOT using Javascript?
I'm using ASP.NET MVC 2
Ok, I think I've found my solution. Basically I am using RedirectToAction if there is a querystring item.
View
<form action="/search/" id="searchForm" method="get">
<input id="searchBox" class="search-gray" name="searchTerms" tabindex="1" onblur=" if (this.value==''){this.value = 'search...'; this.className = 'search-gray'}" onfocus=" this.className = ''; if (this.value=='search...') {this.value = ''}" type="text" maxlength="80" size="28" value="search...">
</form>
Controller
Function Index(Optional ByVal searchTerms As String = "") As ActionResult
If Not Request.QueryString("searchTerms") = "" Then
Return RedirectToAction("Index", "Search", New With {.searchTerms = searchTerms})
End If
ViewData("searchTerms") = searchTerms
Return View()
End Function
No more javascript.

Drupal - Search box not working - custom theme template

I am using a customised version of search-theme-form.tpl
When I use the search box, I do get transferred to the search page. But the search does not actually take place. The search box on the search results page does work though. This is my search-them-form.tpl.php file (demo :
<input type="text" name="search_theme_form_keys" id="edit-search-theme-form-keys" value="Search" title="Enter the terms you wish to search for" class="logininput" height="24px" onblur="restoreSearch(this)" onfocus="clearInput(this)" />
<input type="submit" name="op" id="edit-submit" value="" class="form-submit" style="display: none;" />
<input type="hidden" name="form_token" id="edit-search-theme-form-form-token" value="<?php print drupal_get_token('search_theme_form'); ?>" />
<input type="hidden" name="form_id" id="edit-search-theme-form" value="search_theme_form" />
There is also a javascript file involved. I guess it's use is pretty clear from the code:
function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
function clearInput(e) {
e.value=""; // clear default text when clicked
e.className="longininput_onfocus"; //change class
}
function restoreSearch(e) {
if (trim(e.value) == '') {
{
e.value="Search"; // reset default text onBlur
e.className="logininput"; //reset class
}
}
}
What can be the problem and how can I fix it?
Apparently, you cannot directly modify the HTML in search-theme-form.tpl.php since thats not the right way to do it. So my adding the class and onFocus and onBlur attributes was the problem.
The correct way to do it is to modify the themes template.php file. Basically we will be using form_alter() to modify the form elements. Since using the HTML way is wrong. Take a look at the code below (taken from : here )
<?php
/**
* Override or insert PHPTemplate variables into the search_theme_form template.
*
* #param $vars
* A sequential array of variables to pass to the theme template.
* #param $hook
* The name of the theme function being called (not used in this case.)
*/
function yourthemename_preprocess_search_theme_form(&$vars, $hook) {
// Note that in order to theme a search block you should rename this function
// to yourthemename_preprocess_search_block_form and use
// 'search_block_form' instead of 'search_theme_form' in the customizations
// bellow.
// Modify elements of the search form
$vars['form']['search_theme_form']['#title'] = t('');
// Set a default value for the search box
$vars['form']['search_theme_form']['#value'] = t('Search this Site');
// Add a custom class and placeholder text to the search box
$vars['form']['search_theme_form']['#attributes'] = array('class' => 'NormalTextBox txtSearch',
'onfocus' => "if (this.value == 'Search this Site') {this.value = '';}",
'onblur' => "if (this.value == '') {this.value = 'Search this Site';}");
// Change the text on the submit button
//$vars['form']['submit']['#value'] = t('Go');
// Rebuild the rendered version (search form only, rest remains unchanged)
unset($vars['form']['search_theme_form']['#printed']);
$vars['search']['search_theme_form'] = drupal_render($vars['form']['search_theme_form']);
$vars['form']['submit']['#type'] = 'image_button';
$vars['form']['submit']['#src'] = path_to_theme() . '/images/search.jpg';
// Rebuild the rendered version (submit button, rest remains unchanged)
unset($vars['form']['submit']['#printed']);
$vars['search']['submit'] = drupal_render($vars['form']['submit']);
// Collect all form elements to make it easier to print the whole form.
$vars['search_form'] = implode($vars['search']);
}
?>
In yourthemename_preprocess_search_theme_form - 'yourthemename' will obviously reflect the name of your custom theme. Basically the code is self-explanatory. what with the comments and all.
So, basically thats the way it works.

Resources