i am trying to split each textarea line that starts with "-" or "- " or " -" into individual span element with specific ID 1,2,3,4 etc..
The closest regex code i found is ^-.+ but it wont work for me like it works on:
https://regex101.com/r/yCOvyR/4
My current code is available also here: http://jsfiddle.net/ribosed/468emjct/59/
Thanks for any help.
$(document).ready(function() {
$("#txt").keyup(function() {
entered = $('#txt').val()
lines = entered.split(/\n/);
spans = "";
for (var i in lines) {
spans += "<span style='color:red;'>- " + lines[i] + "</span><br/>";
}
$(".res").html(spans);
});
});
.row {
background: #f8f9fa;
margin-top: 20px;
padding: 10px;
}
.col {
border: solid 1px #6c757d;
}
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
</head>
<body>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<!--
Bootstrap docs: https://getbootstrap.com/docs
-->
<div class="container">
<div class="row">
<div class="col-12">
<form>
<textarea id="txt" rows="5" cols="60" placeholder="Type something here..."></textarea>
</form>
</div>
<div class="col-12 res"></div>
</div>
</div>
</body>
plit and match proces should be achieved while user type in textarea. I tried to use .keyup()
You're not checking the Regex in your code, so it's out of question to ask "why" it's not working.
I think this should work:
$(document).ready(function() {
const regex = /^\s*-\s*/;
$("#txt").keyup(function() {
const entered = $('#txt').val()
const lines = entered.split(/\n/);
let spans = "";
for (const line of lines) {
if (regex.test(line)) {
spans += "<span style='color:red;'>- " + line.replace(regex, '') + "</span><br/>";
}
}
$(".res").html(spans);
});
});
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<div class="container">
<div class="row">
<div class="col-12">
<form>
<textarea id="txt" rows="5" cols="60" placeholder="Type something here..."></textarea>
</form>
</div>
<div class="col-12 res"></div>
</div>
</div>
Related
I'm testing the Youtube Data API V3 to get a list videos by a query term and subsequently play them in an iframe.
I'm getting this error:
www-embed-player.js:306 GET https://googleads.g.doubleclick.net/pagead/id?exp=nomnom net::ERR_BLOCKED_BY_CLIENT
After some debugging and googling, I discovered that this error is often caused by adblockers. I've then disabled mine on Chrome and then retested the api call.
I no longer see the original error :ERR_BLOCKED_BY_CLIENT but my videos retrieved do not play. Player message: An error occurred, please try again later.
Below is the code. The JS is in the HTML file itself for simplicity.
Any help appreciated!
<!doctype html>
<html lang="en">
<head>
<title>Youtube API Test </title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb"
crossorigin="anonymous">
</head>
<style>
body {
background-color: #0F0F0F;
}
button.btn.btn-primary {
background-color: #E12523;
border-color: #E12523;
}
div.jumbotron {
background-color: #292929;
color: #B3B3B3;
}
hr.my-2 {
border: 1px solid #B3B3B3;
}
</style>
<body>
<div class="wrapper container">
<div class="jumbotron">
<h1 class="display-3">Youtube Api</h1>
<p class="lead">Let's use the Yotube Api to get videos</p>
<hr class="my-2">
<form>
<div class="form-group">
<label for="user-query"></label>
<input type="text" class="form-control" id="user-query" aria-describedby="emailHelp" placeholder="Search Youtube">
</div>
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
</div>
</div>
<div class="container" id="results"></div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ"
crossorigin="anonymous"></script>
<script type="text/javascript">
//Get Videos
$("#submit").on("click", function (event) {
event.preventDefault();
var queryTerm = $("#user-query").val().trim();
$.ajax({
url: "https://www.googleapis.com/youtube/v3/search?part=snippet&q=" + queryTerm + "&type=video&key=[MY API KEY]",
method: "GET"
}).then(function (data) {
console.log(data);
$.each(data.items, (i, item) => {
console.log(data.item);
const videoId = item.id.videoId;
let $iFrameContainer = $(`<iframe width="420" height="345" src="https://www.youtube.com/embed/"' ${videoId} '> <\/iframe >`);
$("#results").append($iFrameContainer);
})
});
})
</script>
</body>
</html>
I have seen many questions similar to this one on here but none of them seem to fix the problem I am having.
I keep getting the following error-
Uncaught SyntaxError: Unexpected token <
It says the error is in line one of the js file but the sources only shows a red line on line one of the html file.
Should also mention it is running on a go server.
Thanks a mil!
Here is my HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello, world!</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Sourcing jquery and ajax -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!--external script.js file-->
<script type = "text/JavaScript" src="ChatBot.js"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<style>
body {
padding-top: 65px;
padding-bottom: 100px;
}
</style>
</head>
<body>
<nav class="navbar fixed-top navbar-dark bg-dark">
<a class="navbar-brand" href="#">Eliza chat bot</a>
</nav>
<div class="container-fluid">
<ul class="list-group">
<div class="fixed-bottom bg-dark p-2">
<div class="container">
<div>
<ul class="list-group"></ul>
</div>
<form action="/Chat" method="GET">
<div class="form-group">
<input type="text" class="form-control" id="userInput" placeholder="Talk to eliza...">
</div>
</form>
</div>
</div>
</ul> </div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
and here is my js
const form = $("#userInput");
const listItem = $("#list-group");
//add the keypress function for when the user types an input for eliza to compute
$(document).ready(()=>{
form.keypress(function(event){
const keyCodes = {
ENTER : 13
}
let keyCode = event.keyCode;
//for enter
if(event.keyCode != keyCodes.ENTER){
return;
}
event.preventDefault();
const input = form.val();
form.val(" ");
listItem.append("<li class='list-group-item list-group-item-success'>"+"User : " + input + "</li>");
// GET/POST
const queryParams = {"userInput" : input }
$.get("/Chat", queryParams)
.done(function(response){
var nextListItem = "<li class='list-group-item list-group-item-info'>"+"ELiza : " + response + "</li>";
setTimeout(function(){
listItem.append(nextListItem)
}, 1000);//set timeout to give wait to response
}).fail(function(){
var nextListItem = "<li class='list-group-item list-group-item-danger' >Sorry I'm not home right now.</li>";
list.append(nextListItem);
});
});
});
Does your webserver happen to have a rule where if the requested resources is not found it will default to serving the index.html file? This is a popular configuration for Single Page Applications.
If that is the case, if the server can not find the js file requested it will serve the contents of the html file, which the browser will try parse as JavaScript. Since the first character on the first line of the html file is < you'll get a syntax error since that is not valid JavaScript.
I have a problem with the do-while. When I type into an input form a different number than 15, it still says 'success', but it shouldn't, because the right number is 15. How could I change the do-while to recognize when I type other number than 15? Thanks for any suggestions.
//works when type only 15
do {
var guess = prompt("Guess a number between 1 and 20");
} while (guess !=15)
alert("Success!");
//this part works when I type 15 or different number
function guessWage() {
do {
var guess = document.getElementById("guessNumber")
if (guess.value != 15) {
guess.value = false;
}
} while (guess.value === 15)
alert('you guessed the number');
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Issue App</title>
<link rel="stylesheet" type="text/css" href="wageup.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>While loop</h2>
<h5><span class="badge badge-secondary">Array backwards:</span></h5>
<div class="alert alert-success" role="alert" id="resultMonthly">
</div>
<h5><span class="badge badge-secondary">Array forwards:</span></h5>
<div class="alert alert-info" role="alert" id="resultDaily">
</div>
<h5><span class="badge badge-secondary">Guess, how much full-stack dev earns</span></h5>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">$</span>
<input type="text" class="form-control" placeholder="Type the number" aria-label="Number" aria-describedby="basic-addon1" id="guessNumber">
</div>
<button onclick="guessWage()" type="button" class="btn btn-info">Guess it!</button>
</div>
<!-- Scripts -->
<!-- Jquery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- JS -->
<script type="text/javascript" src="whileloop.js"></script>
</body>
</html>
Ok, I changed the string to Number with Number(var), but now it's giving me an infinite loop. I'm little bit confused. Someone knows what to add into this do-while?
function guessWage() {
do {
var guess = document.getElementById("guessNumber")
} while (Number(guess.value) !== 15)
alert('you guessed the number');
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Issue App</title>
<link rel="stylesheet" type="text/css" href="wageup.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>While loop</h2>
<h5><span class="badge badge-secondary">Array backwards:</span></h5>
<div class="alert alert-success" role="alert" id="resultMonthly">
</div>
<h5><span class="badge badge-secondary">Array forwards:</span></h5>
<div class="alert alert-info" role="alert" id="resultDaily">
</div>
<h5><span class="badge badge-secondary">Guess, how much full-stack dev earns</span></h5>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">$</span>
<input type="text" class="form-control" placeholder="Type the number" aria-label="Number" aria-describedby="basic-addon1" id="guessNumber">
</div>
<button onclick="guessWage()" type="button" class="btn btn-info">Guess it!</button>
</div>
<!-- Scripts -->
<!-- Jquery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- JS -->
<script type="text/javascript" src="whileloop.js"></script>
</body>
</html>
Javascript uses == !=, but you should always use === and !==.
Since the former can have unpredictable results sometimes. Moreover, you are comparing a string to an integer. Try converting them beforehand using Number(var)
Basically what you are trying to achieve is not clear.. if you simply want to compare the values on button click you dont need a loop in that case.so something like..
function guessWage() {
var guess = document.getElementById("guessNumber")
if (guess.value != "15") {
// do what you want here if guess is wrong.
alert('wrong guess');
}
else
{
// do what you want if guess is right
alert('right guess');
}
}
OR
function guessWage()
{
var guess = document.getElementById("guessNumber")
if (Number(guess.value) != 15) {
// do what you want here if guess is wrong.
alert('wrong guess');
}
else
{
// do what you want if guess is right
alert('right guess');
}
}
feel free to comment about if anything is there i will update my answer.
I already have my own solution for this problem, but then I don't know if I'm using the best techniques/practices to solve this particular scenario, which involves removing and adding DOM elements with unique id's.
I have just used jQuery, the requirements where only a button to add any amount of rows, once another row is added be able to delete that row too, the first row is always mandatory, here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> <title>Simple form</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<style type="text/css">
label{
display: block;
}
</style>
</head>
<body>
<div class="container">
<div class="row inputRows">
<div class="col-sm-12" id="newRow-1">
<label>Some label over input</label>
<input type="text" name="txt">
</div>
</div>
<div class="row">
<div class="col-sm-12">
<button id="addRow"><span class="fa fa-plus"></span> Add </button>
<button id="viewInfo"><span class="fa fa-plus"></span> Info </button>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p id="result">
</p>
</div>
</div>
</div>
<script src="https://npmcdn.com/tether#1.2.4/dist/js/tether.min.js"></script>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<script type="text/javascript">
$('.inputRows').on('click', 'button' ,function(){
$(this).parent().remove();
});
$('#addRow').click(function(){
var $newRow = $('div[id^="newRow"]:first').clone(),
newId = Number($('div[id^="newRow"]:last').attr('id').split('-')[1]) + 1;
$newRow.append('<button><span class="fa fa-trash-o"></span></button>');
$newRow.find('input').val('');
$newRow.attr('id','newRow-' + newId);
$('.inputRows').append($newRow);
});
$('#viewInfo').click(function(){
$('#result').text(JSON.stringify(objectifyForm($('div[id^="newRow"]'))));
});
function objectifyForm(formArray) {
var resultArray = {},
inputValue = '';
for (var i = 0; i < formArray.length; i++){
inputValue = $(formArray[i]).find('input').val();
if(inputValue){
resultArray[$(formArray[i]).attr('id')] = inputValue;
}
}
return resultArray;
}
</script>
</body>
</html>
So the code works, the only problem I see is that the numeration of the id's, can sometimes be 1,5,8,7,6,12 depending on which ones you delete, but then it's fine because in the end, it doesn't even matter (joke, RIP Chester, but kind of true). My main concern or question is, is there any other way of achieving this more efficiently using jQuery? Am I doing something wrong by cloning the first element multiple times? If you can share some knowledge on DOM manipulation that would be great.
Thanks in advance,
Leo.
I'm currently making a list that creates categories based on user input through a text field. Each time the create button is clicked my JavaScript is called and adds a div that should be collapsible to show a list.
Right now I only have a button collapsing underneath but there will be additional content after I can get the collapse operational.
HTML: The JQuery UI is for potential drag-drop functionality later:
<link href="main.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.3.0.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<!--
Bootstrap is a lightweight and relativley flexible framework that is great for responsive sites.
Although there are some downsides, as with almost anything, it is great for getting a good looking site up and running quickly.
This would allow this To Do List to be used just as easily on a mobile device while still maintaining an attractive look.
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div class="container">
<div class="h1 row text-center" id="main-header">To Do List</div>
<div class="row" id="category-anchor">
<div role="form" class="form-inline">
<label id="category-label">New Category: </label>
<input type="text" id="new-category" class="form-control">
<button id="create-category" class="btn btn-primary form-control" onClick="createCategory()">Create</button>
</div>
</div>
<li id="anchor">
</li>
</div>
</body>
<script src="todo.js"></script>
</html>
Here is my tiny bit of CSS:
* {
font-family: Serif;
}
#main-header {
font-weight: bold;
background-color: #00ffff;
margin-top: 0px;
}
#category-label {
font-size: 150%;
}
#create-category {
font-weight: bold;
font-family: Sans-serif;
font-size: 100%;
}
li {
list-style-type: none;
}
JavaScript:
var categoryID = 0;
var todoListID = 1000;
function createCategory() {
var newCategory = document.getElementById("new-category").value;
if(newCategory.trim().length != 0) {
var categoryRow = '<div id="' + categoryID + '" class="category">';
categoryRow += '<div class="h2 row text-center" data-toggle="collapse" data-target="#' + todoListID + '">' + newCategory + '</div>';
categoryRow += '</div>';
document.getElementById("new-category").value = "";
}
$(categoryRow).appendTo("#anchor");
addToDoList();
categoryID++;
todoListID++;
}
function addToDoList() {
var list = '<div id="' + todoListID + '" class="list collapse">';
list += '<div class="row">';
list += '<button class="btn btn-success create-list">New ToDo</button>';
list += '</div>';
list += '</div>';
$(list).appendTo("#" + categoryID);
}
If I use "collapse in" the button shows but the above div is still not collapsible.