Function for setting text of an element - javascript

// Function for setting text of an element:
function setText(elementId, message)
{
'use strict';
if ( (typeof elementId == 'string')&& (typeof message == 'string') )
{
var output = $(elementId);
if (output.textContent !== undefined)
{
output.textContent = $(elementId).string;
}
else
{
output.innerText =$(elementId).string ;
}
} // End of main if.
} // End of setText() function.
I need help with this code, I need to define a function name the setText() function as shown below, when I run this code in JS Bin the page shows the code won't run, I couldn't find where the error is. Can anyone give me a hint?

Your type checking for message is unnecessary, but in case you want to keep it:
function setText(elementId, message){
if((typeof elementId == 'string') && (typeof message == 'string')){
document.getElementById(elementId).innerHTML = message;
}
}
setText("foo", "1")
setText("foobar", "2")
setText("bar", "3")
setText("barfoo", "4")
<p id="foo"></p>
<p id="foobar"></p>
<p id="bar"></p>
<p id="barfoo"></p>

You can do it using JavaScript prototypical way. This is little advanced.
HTML:
<span id="spanText"> Your sample Text </span>
First of all augment the type by this code:
/*
Augmenting type
*/
Function.prototype.addMethod = function(funcName, funcBody){
if(!this.prototype[funcName]){
this.prototype[funcName] = funcBody;
return this;
}};
String.addMethod("setText", function(text){
document.getElementById(this).textContent = text;
});
var elementId = "spanText";
elementId.setText("kkkkkkkkkkk");
Load this JS below your HTML file.
You are able to add any of your custom string, number, array method by this way.
See the complete example here:
https://jsfiddle.net/dmsbilas/wu3cd88w/

Related

define a herf link based on if/else scenario in JS file

So basically I'm a beginner in JavaScript and HTML and trying to play with functions call on JS that will edit my HTML file.
Now, I'm trying to redirect users to different pages based on their type.
I want to use "onload" function in order to determine the user type and edit the link according to the result.
HTML:
<body onload="what_user()">
<div id="result">zone</div>
</body>
JS file:
function what_user() {
var d = document.getElementById("result");
var user = ""; // get the user type
if (user == "") d.outerHTML = "" + "";
else d.outerHTML = "" + "";
}
I have some problems understanding how to call a function from HTML and use it on JS as well as return values.
Thanks in advance!!!
Don't play with elements as string. Create an element and put it where you want.
function what_user() {
var d = document.getElementById("result");
let a = document.createElement('a')
a.text = 'zone'
var user = ""; // get the user type
if (user == "") a.href = 'admin_index.html'
else {
a.href = 'admin_user.html'
}
d.parentNode.removeChild(d);
document.body.appendChild(a)
}
<body onload="what_user()">
<div id="result">zone</div>
</body>

JS file not being found in .NET visual studio using Blazor WebAssembly

I am trying to add a JS script file called chatfunction.js into my index.html in Blazor but it gives me an error that it cannot find a file. My CSS is linked correctly and the HTML and CSS both show up but it does not provide any of the JS functionality that I have implemented.
I am adding it at the bottom of my HTML in index.html like this:
....
<script src="_framework/blazor.webassembly.js"></script>
<script src="chatfunction.js"></script>
</body>
</html>
Here is my project structure
Now when I try compiling it gives me this error:
(JS) File 'C:/Users/darka/source/repos/chatproject/wwwroot/js/mysrc.js' not found.
I don't get why it can't find it and I am confused as to why it thinks my file is mysrc.js as there is no file like that in my project structure.
Any pointers how to fix this?
Here is the layout of my JS file
var botController = (function () {
})();
var uiController = (function () {
})();
var controller = (function (botCntr, uiCntr) {
var $chatCircle,
$chatBox,
$chatBoxClose,
$chatBoxWelcome,
$chatWraper,
$submitBtn,
$chatInput,
$msg;
/*toggle*/
function hideCircle(evt) {
evt.preventDefault();
$chatCircle.hide('scale');
$chatBox.show('scale');
$chatBoxWelcome.show('scale');
}
function chatBoxCl(evt) {
evt.preventDefault();
$chatCircle.show('scale');
$chatBox.hide('scale');
$chatBoxWelcome.hide('scale');
$chatWraper.hide('scale');
}
function chatOpenMessage(evt) {
evt.preventDefault();
$chatBoxWelcome.hide();
$chatWraper.show();
}
//generate messages on submit click
function submitMsg(evt) {
evt.preventDefault();
//1. get input message data
msg = $chatSubmitBtn.val();
//2.if there is no string button send shoudn't work
if (msg.trim() == '') {
return false;
}
//3. add message to bot controller
callbot(msg);
//4. display message to ui controller
generate_message(msg, 'self');
}
function chatSbmBtn(evt) {
if (evt.keyCode === 13 || evt.which === 13) {
console.log("btn pushed");
}
}
/* var input = uiCntr.getInput();*/
/* $chatSubmitBtn.on("click", hideCircle);*/
function init() {
$chatCircle = $("#chat-circle");
$chatBox = $(".chat-box");
$chatBoxClose = $(".chat-box-toggle");
$chatBoxWelcome = $(".chat-box-welcome__header");
$chatWraper = $("#chat-box__wraper");
$chatInput = $("#chat-input__text");
$submitBtn = $("#chat-submit");
//1. call toggle
$chatCircle.on("click", hideCircle);
$chatBoxClose.on("click", chatBoxCl);
$chatInput.on("click", chatOpenMessage);
//2. call wait message from CRM-human
$submitBtn.on("click", chatSbmBtn);
$chatInput.on("keypress", chatSbmBtn);
//6. get message from bot controller-back end
//7. display bot message to ui controller
}
return {
init: init
};
})(botController, uiController);
$('.chat-input__form').on('submit', function (e) {
e.preventDefault();
msg = $('.chat-input__text').val();
$('.chat-logs').append('<div id="cm-msg-0" class="chat-msg background-warning push-right bot"><div class="cm-msg-text">' + msg + '</div><span class="msg-avatar"><img class="chat-box-overlay_robot" src="https://www.meetsource.com//userStyles/images/user.png"></span></div>');
$('.chat-input__text').val('');
});
$(document).ready(controller.init);
function talk() {
var user = document.getElementById("userBox").value;
document.getElementById("userBox").value = "";
document.getElementById("chatLog").innerHTML += user + "<br>";
}
I think your script line needs to be:
<script src="js/chatfunction.js"></script>

Testing for special characters JavaScript

Say I have this HTML element:
<td>—</td>
When parsed by browsers, — is converted to an actual em-dash, like so:
<td>—</td>
How can I test for — without using other characters in my JavaScript code?
console.log(elem.innerHTML == "—"); // false
console.log(elem.textContent == "—"); // false
console.log(elem.innerHTML == "—"); // true
console.log(elem.textContent == "—"); // true
You could create a new DOM element, and compare the two:
/**
* Test that a DOM element's inner HTML is === —
*/
function mdashTest(el) {
var tempEl = document.createElement('div');
tempEl.innerHTML = '—';
return el.innerHTML === tempEl.innerHTML;
}
// Test it!
elem = document.getElementById('dash');
alert( mdashTest( elem ) );
<div id="dash">—</div>
The unicode equivalent of emdash is \u2014. You can use this unicode to compare with the html.
The default encoding for HTML meta is set to UTF so all the entities are converted to UTF-8. Read More https://developer.mozilla.org/en/docs/Web/HTML/Element/meta#Attributes
var dash = document.getElementById('dash').innerText;
alert(dash === '\u2014');
<div id="dash">—</div>
I suggest that:
through DOMParser()
function parseToText(code) {
return new DOMParser().parseFromString('<em>' + code + '</em>', "text/html").firstChild.textContent;
}
var is = document.getElementById('text').innerHTML == parseToText("—");
document.write("isEquals ", is, parseToText("—"));
<em id="text">—</em>
Or, with jQuery:
function parseToText(code) {
return $("<em>" + code + "</em>").html()
}
var isEquals = document.getElementById('text').innerText == parseToText("—");
document.write("isEquals ", isEquals);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<em id="text">—</em>
Or, with plain JavaScript:
function parseToText(code) {
return document.createRange().createContextualFragment(code).firstChild.textContent;
}
var isEquals = document.getElementById('text').innerText == parseToText("—");
document.write("isEquals ", isEquals);
<em id="text">—</em>

New to HTML5 and JavaScript, and I can't connect JavaScript file to HTML file?

So I am having a problem with HTML5 and javascript.
I made a few .js files for the javascript part and I made the link to connect it with the HMTL code but it will not show the javascript part.
This is my HTML
<!doctype html>
<html lang="en">
<head>
<title>Gateway Tunes</title>
<meta charset="utf-8" />
<script src="playlist_store.js"></script>
<script src="playlist.js"></script>
</head>
<body>
<form>
<input type="text" id="songTextInput" size="40" placeholder="Song name">
<input type="button" id="addButton" value="Add Song">
</form>
<ul id="playlist">
</ul>
</body>
</html>
and here are my javascript files; the names of the files are at the top
playlist_store.js
function save(item) {
var playlistArray = getStoreArray("playlist");
playlistArray.push(item);
localStorage.setItem("playlist", JSON.stringify (playlistArray));
}
function loadPlaylist() {
var playlistArray = getSavedSongs();
var ul = document.getElementById('playlist");
if (playlistArray !Null) {
for (var i = 0; i < playlistArray.length; i++) {
li.innerHTML = playlistArrray[i];
ul.appenChild(li);
}
}
}
function getSavedSongs() {
return getStoreArray("playlist")
}
function getStoreArray (key);
var playlistArray = localStorage.getItem(key);
if(playlistArray == null || playlistArray == "") {
playlistArray = new Array();
}
else {
playlistArray = JSON.parse (playlistArray);
}
return playlistArray;
}
playlist.js
window.onload = init;
function init() {
var button = document.getElementById ("addButton");
button.onclick = handleButtonClick;
loadPlaylist();
}
function handleButtonClick () {
var textInput = document.getElementById("songTextInput");
var songName = textInput.value;
if (songName == "") {
alert("Button was clicked!");
}
else {
alert("Your track has been added!");
}
var li = document.createElement("li");
li.innerHTML = songName;
var ul = document.getElementById("playlist");
ul.appendChild(li);
save (songName);
}
You've got some syntax errors so your javascript isn't running.
In playlist_store.js
var ul = document.getElementById('playlist");
Opens a string with ' but tries to close it with ". It doesn't matter which you use as long as you're consistent, so you can either change it to 'playlist' or "playlist".
if (playlistArray !Null) {
If you're trying to make sure playlistArray isn't null you can do
if (playlistArray != null) {
notice != as the comparison and null needs to be lowercase. If you want to make sure it isn't just undefined or null you can simply do if (!playlistArray).
ul.appenChild(li); needs to be ul.appendChild(li);.
I'm sure there's more, check over your code.
The first line of your script (and the only one that isn't just a function definition) is window.onload = init;. This means that after the page has loaded, your init function is called.
This function looks up the element with id addbutton, and then calls a method on the returned result. Since you don't have an element with this ID, there won't be any object returned, and so an exception will be thrown (something like "button is null or not an object", depending on your browser). This exception stops the method from executing further - and in particular, loadPlaylist() will not be called.
The moral of the story here though is pay attention to the JavaScript error console, especially while you're doing development! You browser will almost certainly have displayed a red exclamation mark icon or similar, which you could double-click to give you the name, message and location of the exception.
You really don't need to post your code listing on Stack Overflow to ask us what's wrong with it, when your browser is already capable of telling you exactly where the problem is.

jQuery issue in IE

Hello I'm using this function as an address book module, for selecting any employee from the sidebar it display all the content of the employee. It works fine in Chrome but not in IE. I'm not able to run the src variables declared in this function in IE. Please suggest me some other ways to declare these type of variables so that these will be compatible to all browsers.
function singleSelect(id)
{
if(flag){
unCheckAll();
userIds="";
//userIds= document.forms['frmSidebarSearch'].elements['userIds'].value + id +",";
var src = ($("#"+id).attr("src") === "<#core.basePath/>images/chk-box-img.gif")
? "<#core.basePath/>images/chk-box-img-tick.gif"
: "<#core.basePath/>images/chk-box-img.gif";
$("#"+id).attr("src",src);
var src2 = ($("#anchor"+id).attr("class") === "")
? "selected"
: "";
$("#anchor"+id).removeClass().addClass(src2);
var elementss = document.getElementById("all").getElementsByTagName('img');
for(i=0;i<elementss.length;i++) {
if($("#"+elementss[i].id).attr("src") === "<#core.basePath/>images/chk-box-img-tick.gif"){
userIds= userIds +"," +elementss[i].id;
}
}
unHilightAll();
highLightIndex(id);
document.forms['frmSidebarSearch'].elements['userIds'].value=userIds;
$('#frmSidebarSearch').ajaxSubmit({target:'#content',url:'<#core.basePath/>sp/manager/manageraddressbook/manager/'+id});
}
flag = true;
}
Have you tried it with double equals (I think triple equals sign is only in languages like php).
(condition == condition) ? true : false;

Categories