0

I am working on an asp.net mvc application. I need to know how to use global javascript variables inside html code. I know global variables are not an ideal solution to a problem but for my solution to work I need them.

I know about their declaration. Here is an example of how I want to use them. I want to use the global js variable to be already filled in at the input.

var title;
function foo(b) {
  title = b;
};
<input type="text" value=title readonly>

Any help will be appreciated. Thanks.

5
  • Do you want to set the value of title into the input's attribute value? if so, you didn't call that function as well as you're only setting a string "title" to the attribute value. Commented Jul 4, 2019 at 7:15
  • for my solution to work I need them - then your solution is wrong. Commented Jul 4, 2019 at 7:18
  • You need to put an identifier for your field, e.g. id="my-input". Then from the JavaScript global scope you may use document.getElementById('my-input').value = title; Commented Jul 4, 2019 at 7:20
  • @chrispbacon Don't be so arrogant. This might not be an XY problem. The OP asks about using a JS value in CSS, not whether global variables are evil. Commented Jul 4, 2019 at 7:20
  • Why does the title talk about CSS when there is no CSS in the question? I assume an edit has been made? Commented Jul 4, 2019 at 7:48

2 Answers 2

4

var title;

function foo(b) {
  document.getElementById("title").value = b;
};

foo("irin")
<input type="text" id="title" readonly>

Sign up to request clarification or add additional context in comments.

Comments

3

Use the setProperty function of the style object of any HTMLElement object

"use strict";

// Note the double quotation '" and "'
// I won't work without, if you want to use the value
// with CSS content rule
const title = '"My title"';
document.getElementById('title').style.setProperty('--title', title);
div {
  padding: 5px;
  border: 1px solid gold;
}

div:before {
  content: var(--title, 'not set');
}
<div id="title"></div>

In the above example I used a [CSS custom Property][1], but you could do without

"use strict";

const title = '"My title"';

const style = document.createElement('style');
style.textContent = `#title:before {
  content: ${title};
}`;
document.head.append(style);
div {
  padding: 5px;
  border: 1px solid gold;
}
<div id="title"></div>

1 Comment

@chrispbacon You are right. I overread this. I only read the title which involves CSS. Then I started coding. But I'll leave this for other people to maybe be of use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.