I want to copy a US format phone number and paste it to my field .
If I copy (456)-123-0596 to the field only 456123 is copied to the field.
But I want it to be like the format.
The input field is restricted only for numbers using pattern and maximum length is 10.
onCheckInput(e) {
const onlyNums = e.target.value.replace(/[^0-9]/g, '');
if (onlyNums.length < 10) {
e.target.value = onlyNums;
} else if (onlyNums.length === 10) {
const number = onlyNums.replace(/(\d{3})(\d{3})(\d{4})/, '($1) -$2-$3');
e.target.value = number;
}
}
formatPhoneNumber(number) {
if (number && number != 0) {
number = number.replace(/-/g, '');
number = number.replace('(', '');
number = number.replace(') ', '');
number = number.replace(')', '');
return '(' + number.substr(0, 3) + ')-' + number.substr(3, 3) + '-' + number.substr(6, 4);
}
return '';
}
<Field name="HomePhone"
onInput={this.onCheckInput} maxLength="10"
pattern="\d*" component="input" type="text"
placeholder="HomePhone"
title={' Home Phone: ' + this.formatPhoneNumber(patientInfo.HomePhone)}
/>
How can I remove the braces and hyphens on Paste and save them in the Phone number format?
I've modified the code as below:
onCheckInput(e) {
const onlyNums = e.target.value.replace(/[^0-9]/g, '');
if (onlyNums != e.target.value.replace(/[^\d\.]/g,""))
{onlyNums.replace(/[^\d\.]/g,"");
}
if (onlyNums.length < 10) {
e.target.value = onlyNums;
} else if (onlyNums.length === 10) {
const number = onlyNums.replace(/(\d{3})(\d{3})(\d{4})/, '($1) -$2-$3');
e.target.value = number;
}
}
When I debugged I found that
Since maxLength1s 10 (456)-123- is read and removed braces and hyphens from this input.
How can I get this format with maxLength=10?
I think this approach can solve your problem:
Listen paste event, when it happens increment maxLength property to 1000, then clean the input and set it again to the input value.
I have implemented it in plain DOM because I don't know react, you can use the same approach to implement it in React
const input = document.querySelector('#HomePhone');
input.addEventListener('paste', (event) => {
// Imcrement maxLengt temporally so user can paste input with ( -
input.maxLength=1000
setTimeout(()=>{
// clean input: only get numbers
const result = input.value.replace(/[^\d]/g,'')
// set the clean input into input value
input.value=result
// reset maxLength to 10
input.maxLength=10
}, 1);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input name="HomePhone" id="HomePhone" maxLength="10" type="text" pattern="\d*" />
</body>
</html>
Related
So I have a script that will sum the values of checkboxes on my page, but I'm having trouble figuring out how to write an if/else if statement based on the value returned. I think the script would look something like this, but the fine folks on here seem to be pretty knowledgeable so any tips would be great!
Thanks in advance!
$(document).ready(function() {
function updateSum() {
var total = 0;
$(".sum:checked").each(function(i, n) {total += parseInt($(n).val());})
$("#total").val(total);
}
if (total == 0) {
"<input type="text" value="Great Job">";
else if (total == 3) {
"<input type="text" value="Good">";
else
"<input type="text" value="Ok">";
}
// run the update on every checkbox change and on startup
$("input.sum").change(updateSum);
updateSum();
})
I'd like markdown links to have a favicon within the transformed link.
https://www.google.com/s2/favicons?domain=http://cnn.com
- will return the favicon from any domain.
Marked (https://github.com/chjj/marked)
- will turn all links in my code to a href's
http://cnn.com
becomes
http://cnn.com
So, How would I modify marked.js so that
- http://cnn.com
will become
<img src="https://www.google.com/s2/favicons?domain=http://cnn.com">http://cnn.com
I do see this line 452 marked.js
autolink: /^<([^ >]+(#|:\/)[^ >]+)>/,
Ref: https://github.com/chjj/marked/blob/master/lib/marked.js
I'm using expressjs and NodeJS
Thanks
Rob
You can override a renderer method.
Marked works in two steps: (1) it parses the Markdown into a bunch of tokens and (2) it renders those tokens to HTML. As you don't want to alter the Markdown parsing (it already properly identifies links), but you do want to alter the HTML output, you want to override the renderer for links.
var renderer = new marked.Renderer();
get_favicon = function (text) {
// return replacement text here...
var out = '<img src="https://www.google.com/s2/favicons?domain='
out += text + '">' + text + '</a>'
return out
}
renderer.link = function (href, title, text) {
if (this.options.sanitize) {
try {
var prot = decodeURIComponent(unescape(href))
.replace(/[^\w:]/g, '')
.toLowerCase();
} catch (e) {
return '';
}
if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
return '';
}
}
var out = '<a href="' + href + '"';
if (title) {
out += ' title="' + title + '"';
}
out += '>' + get_favicon(text) + '</a>';
return out;
};
}
// Pass the custom renderer to marked with the input.
markdown(input, renderer=renderer)
Note that I just took the default link method and altered it slightly to pass text through the get_favicon function. The get_favicon function accepts a text string and returns the replacement text (an image in this case). It could probably be improved as not all links will only have a domain as their text content. If the text contained more that the domain (path, fragment, query string, etc), then only use the domain for the favicon link. Or if the text did not contain a link at all (as the same renderer is used for all links, not just auto links) then the text should be returned unaltered. I'll leave those improvements as an exercise for the reader.
You don't have to mess with marked source code.
This simple regexp should do the trick:
const markedOutput = 'http://cnn.com';
const withFavIcons = markedOutput.replace(/(<a[^>]+>)(https?:\/\/[^<]+)(<\/a>)/gi, (m, open, url, close) => {
const favicon = '<img src="https://www.google.com/s2/favicons?domain=' + url + '">';
const truncated = url.length > 50 ? url.slice(0, 47) + '...' : url;
return open + favicon + truncated + close;
});
I am hoping someone more knowledgeable here can point out what the problem is.
I am making a custom menu for Drupal7 for a particular theme I am working on, which is using the menu_views module. Everything works pretty nicely until I pass the view menu entry over to menu_views to parse, in which case drupal adds a broken <div class=">...</div> around the parent UL element of the view menu.. I have gone through the code and don't see how this is even happening.. If I comment out the call to the view parsing, then it doesn't add this DIV, but that view parsing shouldnt' be touching the parent UL element?
Here is how the HTML is output:
<ul class="sub-menu collapse" id="parent_">
<div class="> <li class=" first=" " expanded=" " active-trail "=" ">Por nome
<ul class="menu-content collapsed in " id=" ">
<div class="view view-nameofview view-id-nameofview etc ">
<div class="view-content ">
<div class="item-list ">
<ul class="views-summary ">
<li>Á
</li>
</ul>
</div>
</div>
</div>
</ul>
</div>
</ul>
Here is the template code that causes this:
function bstheme_menu_link__main_menu($variables) {
$element = $variables['element'];
// resolve conflict with menu_views module
if (module_exists('menu_views') && $element['#href'] == '<view>') {
return _bstheme_menu_views_menu_link($variables); //<<<< IF I COMMENT OUT THIS THE OUTPUT IS FINE
}
static $item_id = 0;
// Add an ID for easy identifying in jquery and such
$element['#attributes']['id'] = 'menu_'.str_replace(' ', '_',strtolower($element['#title']));
if(!empty($element['#original_link']['menu_name']) && $element['#original_link']['menu_name'] == 'main-menu'){
if($element['#original_link']['has_children'] == 1){
$element['#attributes']['data-target'] = "jquery_updates_this";
$element['#attributes']['data-toggle'] = "collapse";
}
// add class parent and remove leaf
$classes_count = count($element['#attributes']['class']);
for($i=0;$i<$classes_count;++$i){
if($element['#attributes']['class'][$i] == 'expanded'){
//$element['#attributes']['class'][$i] = 'collapse';
}
if($element['#original_link']['plid'] == 0){
if($element['#attributes']['class'][$i] == 'leaf'){
unset($element['#attributes']['class'][$i]);
}
}
else{
if($element['#attributes']['class'][$i] == 'leaf'){
$element['#attributes']['class'][$i] = '';
}
}
}
}
// code to add a span item for the glythicons
$switch = $element['#original_link']['has_children'];
$element['#localized_options']['html'] = TRUE;
if($switch == 1) {
$linktext = $element['#title'] . '<span class="arrow"></span>';
} else {
$linktext = $element['#title'];
}
// if there's a submenu, send the parsing to the custom function instead of the main one to wrap different classes
if ($element['#below']) {
foreach ($element['#below'] as $key => $val) {
if (is_numeric($key)) {
$element['#below'][$key]['#theme'] = 'menu_link__main_menu_inner'; // 2 lavel
}
}
$element['#below']['#theme_wrappers'][0] = 'menu_tree__main_menu_inner'; // 2 lavel
$sub_menu = drupal_render($element['#below']);
$element['#attributes']['class'][] = 'menu-toggle';
}
//$sub_menu = $element['#below'] ? drupal_render($element['#below']) : '';
$output = l($linktext, $element['#href'], $element['#localized_options']);
return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . '</li>'."\n";
}
function _bstheme_menu_views_menu_link(&$variables) {
// Only intercept if this menu link is a view.
$view = _menu_views_replace_menu_item($variables['element']);// <<< MENU VIEWS PARSING
if ($view !== FALSE) {
if (!empty($view)) {
$sub_menu = '';
if ($variables['element']['#below']) {
$sub_menu = render($variables['element']['#below']);
}
return '' . $view . $sub_menu . "\n"; // <<< RETURN PATH
}
return '';
}
return theme('menu_views_menu_link_default', $variables);
}
Any pointers on how to troubleshoot something like this, or if someone has encountered this problem before and has a solution, would be greatly helpful!
From your code, it's apparent you're using Drupal 7.
First things first, you may want to enable theme debug mode. This allows for you to see where the theming function that caused your
You can do so by putting the following line in your settings.php file
$conf['theme_debug'] = TRUE;
Flush your caches after you make this change.
You will now have debug code output to your Drupal HTML source, when you view the site's source. An example of the type of output is shown below:
<!-- THEME DEBUG -->
<!-- CALL: theme('page') -->
<!-- FILE NAME SUGGESTIONS:
x page--front.tpl.php
* page--node.tpl.php
* page.tpl.php
-->
With this debug, you should be able to see exactly which theme functions run, in which order, and by working through them from start to finish, you should be able to determine between which theme is responsible.
At this point, if you want to keep Drupal-best-practices, copy the file name suggestion from the debug output to a folder inside your theme folder. I usually put all template overrides in a sub-directory inside it.
In the case above, if it was page.tpl.php, I'd copy it to /themes/mytheme/templates/, and go hack on it to see whether the offending div is being generated there.
Best of luck, and if you hit a stuck end, I'd be happy to help point you in a direction more specific to your specific user case.
Best,
Karl
I have implemented intro.js to my website. But I wanted to start the tour only on first visit. may be by using cookies.. website is made with html no php..
JavaScript cookies are a solution although I should point out that it will only work for as long as the user keeps the cookie.
//set the cookie when they first hit the site
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
//check for the cookie when user first arrives, if cookie doesn't exist call the intro.
function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1)
{
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1)
{
c_value = null;
}
else
{
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1)
{
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
code is from http://www.w3schools.com/js/js_cookies.asp
obviously there's some blanks you'll have to fill in there, but it's a good starting point for working with cookies in javascript.
EDIT:
So you want to make a new function, put it in the head, inside script tags (if you have them already, just copy the function into there (you'll want to put the other two functions I provided within the script tag also)). This function will check to see if you have a cookie. If you do, just return. If you don't, create the cookie and run the intro,
<head>
<script type="text/javascript">
function checkCookieIntro(){
var cookie=getCookie("mySite");
if (cookie==null || cookie=="") {
setCookie("mySite", "1",90);
runIntro(); //change this to whatever function you need to call to run the intro
}
}
</script>
</head>
now change your body to be:
<body onload="checkCookieIntro()">
so when the body loads it will check to see if a cookie exists, if it doesn't, create a cookie with a value of one that will last for 90 days (unless the user deletes it) and then run the intro. If the cookie does exist with a value then it does nothing.
For a project im building a navigation. The table is like this
SELECT TOP 1000
[id]
,[title]
,[action]
,[listOrder]
,[fk_parentId]
FROM [portfolio].[dbo].[menu]
Where Fk_parentId refers to a id... to build up a menu with levels. Listorder contains a number
Now i want my navigation to output like this
<ul class="nav nav-list">
<li class="nav-header active">List header</li>
<li class="active">Home</li>
<li>Library</li>
<li>Applications</li>
<li class="nav-header">Another list header</li>
<li>Profile</li>
<li>Settings</li>
<li class="divider"></li>
<li>Help</li>
</ul>
so the nav headers must be detected as a nav header and menu items as child. For now i have this code
public void function main(struct rc) {
queryService = new query();
queryService.setDatasource("portfolio");
result = queryService.execute(sql="SELECT * FROM menu ORDER by listOrder");
// result
GetMenuData = result.getResult();
// Loopen over result
writeOutput("<ul class='nav nav-list>'");
for (i = 1; i LTE GetMenuData.RecordCount; i = (i + 1))
{
// Output
WriteOutput(
"<li><a href='"& GetMenuData[ "action" ][ i ] & "'>" & GetMenuData[ "title" ][ i ] & "</a></li>"
);
}
writeOutput("</ul>'");
}
this results:
<ul class='nav nav-list>'
<li><a href='alk.profile'>PROFILE</a></li>
<li><a href=''>List header</a></li>
<li><a href='main.'>home</a></li>
<li><a href=''>Another List header</a></li>
<li><a href='alh.settings'>settings</a></li>
<li><a href='main.library'>librarY</a></li>
<li><a href='help.main'>Help</a></li>
<li><a href='main.applications'>applications</a></li>
</ul>'
How can I add class header to a "header" <li> like listheader, another list header?
How can i dynamicly add the divider between settings and help?
title action listOrder fk_parentId
Another List header NULL 20 NULL
PROFILE alk.profile 5 539BB1A4-5AB5-4059-93AD-17DD8EABAF60
Help help.main 40 NULL
settings alh.settings 20 539BB1A4-5AB5-4059-93AD-17DD8EABAF60
applications main.applications 50 C5EFAE69-FD2A-4B35-A613-B8D429091A8F
List header NULL 10 NULL
home main. 20 C5EFAE69-FD2A-4B35-A613-B8D429091A8F
librarY main.library 30 C5EFAE69-FD2A-4B35-A613-B8D429091A8F
I can't see how you specify active from what you posted, but the following at least would result in the function returning the list with header classes.
public string function main(struct rc) {
// Set up the return string
var strReturn = '<ul class="nav nav-list">';
// Set up the query
var queryService = new Query(
datasource='portfolio'
);
// Execute and get result, specifying field names
var GetMenuData = queryService.execute(sql='
SELECT
id,
action,
title,
fk_parentId
FROM menu
ORDER by listOrder ASC
').getResult();
// Loop over result
for (var i = 1; i <= GetMenuData.RecordCount; i++) {
// For this result, what classes are needed?
var strClasses = '';
// Header class
if (
Len(GetMenuData['fk_parentId'][ i ]) == 0 // Null / len 0 parent == header
) {
strClasses = ListAppend(strClasses,'nav-header',' ');
}
// Add in some logic here for 'active' later on probably a good idea?
// strClasses = ListAppend(strClasses,'active',' ') if id == active id? May need adjustment to query for parent
if (
Len(strClasses) > 0
) {
strClasses = ' class="'&strClasses&'"';
}
// Output list item
strReturn &= '<li'&strClasses&'>';
// Add href if needed
if (
Len(GetMenuData['action'][ i ]) > 0
) {
strReturn &= '<a href="'&GetMenuData['action'][ i ]&'">';
}
strReturn &= GetMenuData['title'][ i ];
if (
Len(GetMenuData['action'][ i ]) > 0
) {
strReturn &= '</a>';
}
// Close off the list item
strReturn &= '</li>';
}
// End the return string
strReturn &= '</ul>';
// And return it
return strReturn;
}
A few notes on the changes
Changed function to have return type "string" instead of "void" and modified it so it returns a string instead of directly writing. This in general allows more control over where precisely the list would be output.
Added scoping for all variables invoked within the function (using 'var' keyword). Please note that the below example will only work in CF9/railo. If using a previous version then the var definitions need to be at top of the function, if unsure just ask
Left a space to indicate where you would add in logic for flagging "active"
Used i++ in place of i = (i + 1) (see What is the difference between ++i and i++? for some info for what that does)
Used strReturn &= ... to add to string, functionally equivilant to strReturn = strReturn & ....